I am trying to convert a valid JSON file to XML.
InputStream is = new FileInputStream(file);
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
String line = buf.readLine(); StringBuilder sb = new StringBuilder();
while(line != null){
sb.append(line);
line = buf.readLine();
}
//form the string
String jsonStr = sb.toString();
//save to xml
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsonStr);
String xml = XML.toString(json);
Here is my dependencies:
import org.json.XML;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
The input JSON is like this:
{"created":"2016-12-22T10:46:40.584Z","createdBy":"ish"}
The output XML looks like:
"{"createdBy":"ish","created":"2016-12-22T10:46:40.584Z"}"
Your problem is that you mix two APIs : json-simple and org.json.
Here :
String xml = XML.toString(json);
You pass a org.json.simple.JSONObject object to the org.json.XML.toString(Object) method.
What you want to pass is a org.json.JSONObject.
Actually, you don't need to use json-simple as you can create a JSONObject with org.json and more particularly a org.json.JSONObject. Which finally is a very good thing as XML.toString() would produce the expected result with an instance of that.
So change your code such as :
JSONObject json = new JSONObject(jsonStr);
String xml = XML.toString(json);
Optionally you can add the tag name of the enclosing element :
String xml = XML.toString(json, "foo");
Note that XML.toString(Object) is not necessary a very good designed API.
It accepts an Object as parameter and so relies on instanceof to apply the suitable processing.
The mapping to XML is done only if the parameter type belongs to some specific types : org.json.JSONObject, org.json.JSONArray, Java array.
And if it is not the case, a single thing is do : special characters are escaped such as ". As a org.json.simple.JSONObject doesn't make part of the expected type, the " of the JSONObject parameter were kept and the escaping converted them to ". Whereas the weird result you get :
"{"createdBy":"ish","created":"2016-12-22T10:46:40.584Z"}"
Related
I am trying to parse a JSON response using jsonObject library in Java, but receiving exception with duplicated key. I need to parse this JSON as it is, without any loop and without any conversion. Some solution stated that I have to convert those values to array, so I need your suggestion. Is there any library that can parse my json which has duplicated key without any change?
This is my code :
BufferedReader in = new BufferedReader(
new InputStreamReader(c.getInputStream())); //stream to resource
String inputLine;
StringBuffer res = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
res.append(inputLine);
}
JSONObject json = new JSONObject(res.toString());
my error response :
Exception in thread "main" org.json.JSONException: Duplicate key "Account"
at org.json.JSONObject.putOnce(JSONObject.java:1121)
at org.json.JSONObject.<init>(JSONObject.java:208)
at org.json.JSONTokener.nextValue(JSONTokener.java:362)
at org.json.JSONObject.<init>(JSONObject.java:208)
at org.json.JSONTokener.nextValue(JSONTokener.java:362)
you can make use of net.sf.json.JSONObject. It will accept JSON with the duplicate key.
This library will retain the duplicated values by storing them into arrays. If multiple same keys are available it will create one key with all the values as Array.
And also the coding part is just a single line. Once you parsed the json using net.sf.json.JSONObject then you can supply this to jackson library.
JSONObject jsonObject = JSONObject.fromObject( "{ \"a\": \"a\", \"a\": { \"b\": {},\"b\": true}}" );
System.out.println( "net.sf.json.JSONObject: " + jsonObject );
JsonNode jsonNode = new ObjectMapper().readTree( jsonObject.toString() );
System.out.println( "com.fasterxml.jackson.databind.JsonNode" + jsonNode );
Output:
net.sf.json.JSONObject: {"a":["a",{"b":[{},true]}]}
com.fasterxml.jackson.databind.JsonNode{"a":["a",{"b":[{},true]}]}
Maven dependency of net.sf.json
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
So, I am trying to make a JsonObject using org.json library, from a string.
This is the code I am using:
StringBuilder line = new StringBuilder();
while (fScanner.hasNextLine()) {
line.append(fScanner.nextLine());
}
System.out.println(line);
JSONObject jsonObject = new JSONObject(line);
System.out.println(jsonObject.toString());
But the output I am getting is showing, empty JsonObject but correct string. It looks like this:
{"username": "Sam","name": "Sam Anderson","points": "150"}
{}
I'm having a problem with Json file reading and writing. I want to append something into a json file but it doesn't work properly: it just put in a new jsonobject without the ',' to divide it from the previous one. I searched everywhere, on every site, but nothing that gave me an input on how to do it properly.
For example, I have a json file like this:
{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
}
}
And I want to make it appear like this:
{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
},
"Example1":{
"Ok":"Ok2",
"Nice":"Nice2",
"Hi":"Hi2",
"Hello":"Hello2",
"Right":"Right2",
"Wow":"Wow2"
}
}
So, I tried using this code:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonObject jsonObject = new JsonObject();
JsonObject dati = new JsonObject();
dati.addProperty("Cognome", StringUtils.capitalize((fields[0].getText())));
dati.addProperty("Nome", StringUtils.capitalize((fields[1].getText())));
dati.addProperty("Sesso", lblSesso.getText());
dati.addProperty("Luogo di nascita", StringUtils.capitalize((fields[2].getText())));
dati.addProperty("Provincia", lblProvincia.getText());
dati.addProperty("Data di nascita", fieldDDN.getText());
jsonObject.add(codfis, dati);
String json = gson.toJson(jsonObject);
try (BufferedReader br = new BufferedReader(new FileReader("CodFisCalcolati.json"));
BufferedWriter bw = new BufferedWriter(new FileWriter("CodFisCalcolati.json", true))) {
String jsonString = gson.fromJson(br, JsonElement.class).toString();
JsonElement jelement = new JsonParser().parse(jsonString);
JsonObject jobject = jelement.getAsJsonObject();
jobject.add(codfis, dati);
String resultingJson = gson.toJson(jelement);
bw.write(resultingJson);
bw.close();
} catch (IOException e1) { e1.printStackTrace(); }
But when I use it, it give me this output :
{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
}
}{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
},
"Example1":{
"Ok":"Ok2",
"Nice":"Nice2",
"Hi":"Hi2",
"Hello":"Hello2",
"Right":"Right2",
"Wow":"Wow2"
}
}
That's output, you see, it'wrong and i don't know how to make the code to give me a different output.
I'm using Gson 2.8.5 and I would rather not change to another library.
You change the question but now the answer to your new question is you use the same file to read and write. That's why you add the data inside ot the file. Change the name of the file that you write and see if you have problems
Please check if "br" is not null.
According to the specification of the method fromJson it returns:
an object of type T from the string. Returns null if json is null.
If this is the case than you call on the null toString() method and you get null pointer exception
In order to find out weather the JSON element is JSONArray or JSONObject type, I am getting Unexpected token END OF FILE at position 0 error.
My JSON is:
{"colors":[{"color":"red","value":"#00"},{"color":"white","value":"#000g"}]}
My code is:
java.io.FileReader reader = new java.io.FileReader("jsonpath");
org.json.simple.parser.JSONParser parser = new JSONParser();
System.Out.Println("aaaaaa JSON Class: "+parser.parse(reader).getClass());
if(parser.parse(reader) instanceof org.json.simple.JSONArray)
System.Out.Println("JSONArray");
else if(parser.parse(reader) instanceof org.json.simple.JSONObject)
System.Out.Println("JSONObject");
When I run above code it shows this output
aaaaaa JSON Class: class org.json.simple.JSONObject Unexpected token END OF FILE at popsition 0
at org.json.simple.parser.JSONParser(Unknown Source)
.
.
.
<rest of the exception>
I don't understand why this exception is occurring.
Please help me out.
Some more details after edit:
My this code is working fine with the given json file:
java.io.FileReader reader = new java.io.FileReader("jsonpath");
org.json.simple.parser.JSONParser parser = new JSONParser();
org.json.simple.JSONObject object = (JSONObject)parser.parse(reader);
System.Out.Println("JSONObject: "+object);
org.json.simple.JSONArray array = (JSONArray)object.get("colors");
System.Out.Println("JSONArray: "+array);
Output of above code:
JSONObject: {"colors":[{"color":"red","value":"#00"},{"color":"white","value":"#000g"}]}
JSONArray: [{"color":"red","value":"#00"},{"color":"white","value":"#000g"}]
But I want to dynamically parse the JSON without knowing the JSON structure.
I want to do something like this:
if(json is object)
JSONObject object = (JSONObject)parser.parse(reader);
else if (json is array)
JSONArray array = (JSONArray)parser.parse(reader);
Thanks.
You're repeatedly parsing the same Reader. The first call exhausts it and then each subsequent call sees an empty stream.
Parse the reader only once. Here is the working code:
java.io.FileReader reader = new java.io.FileReader("jsonpath");
org.json.simple.parser.JSONParser parser = new JSONParser();
Object p = parser.parse(reader);
if(p instanceof org.json.simple.JSONArray){
System.Out.Println("JSONArray");
org.json.simple.JSONArray object = (JSONArray)p;
}
else if(p instanceof org.json.simple.JSONObject){
System.Out.Println("JSONObject");
org.json.simple.JSONObject object = (JSONObject)p;
}
Output of above code
JSONObject
Well, error may occur when you try to pass wrong path.
So check your path to json file properly. Try to use absolute path at first.
Here is my procedure:
private static void ReadWithEncoding(String filePath, String encoding) {
StringBuilder json = new StringBuilder();
File f = new File(filePath);
if (f.exists() && f.isFile()) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), encoding));
String line;
while ((line = br.readLine()) != null) {
json.append(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(json);
}
}
You may run it like this for UTF8:
ReadWithEncoding("D:/file.json", "UTF8");
For Cyrillic symbols:
ReadWithEncoding("D:/file.json", "Cp1251");
I too was getting this error ("Unexpected token END OF FILE at position 0.").
I was using same instance of com.google.gson.Gson and org.json.simple.parser.JSONParser on multiple threads.
Now I changed the code and created new instance of these on each thread, and that solved the issue.
gson = new GsonBuilder().create();
parser = new JSONParser();
I'm using Bing's auto suggest feature to auto suggest me terms given a query. You can find the tool here: http://api.bing.com/osjson.aspx?query=pe as you can see it's returning a strange format that isn't quite JSON. Is this a specific standard different to JSON? I've attempted parsing it as JSON using...
InputStream i = new URL(url).openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(i, Charset.forName("UTF-8")));
JSONObject json = new JSONObject(readAll(reader));
but I get the error A JSONObject text must begin with '{' found:" at 2 [character 3 line 1]
readAll =
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
Your example is valid JSON:
["pe",["people","people search","petsmart","petco","petfinder","pep boys","people finder","people of walmart"]]
It is not object, it is array, which contains string at the first position and another array at the second. So try parse as JSONArray, not as JSONObject.
A JSON Object starts with a { and ends with a }, which a JSONObject class was designed to parse.
A JSON Array starts with a [ and ends with a ], which a JSONArray class was designed to parse.
I hope this helps.