Why am I getting a JsonSyntaxException here? - java

I am experiencing a JSON parsing error. My code is as follows:
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<JsonObject> posts = (List) gson.fromJson(reader, JsonObject.class);
Log.e(TAG, "Results Size: " + posts.size());
// for(int i=0; i<posts.size(); i++){
// Log.e(TAG, "Checking: " + posts.get(i).title());
// }
content.close();
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
}
I get the following error from my posts.size() check:
Failed to parse JSON due to: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
For the JSON I am trying to read, if successful my posts.size() should be returning 5.
What am I doing wrong here?

I think your problem stems from the fact that you're trying to deserialize to a generic type (a List). The documentation states that in this case you need to pass in a Type rather than a Class to the fromJson() method. Try this:
Type type = new TypeToken<List<JsonObject>>(){}.getType();
List<JsonObject> posts = gson.fromJson(reader, type);

As it mentions in the exception line, your JSON starts with [ so it indicates a JSON Array rather than a JSON Object, but JSON have to start with a JSON Object. So wrap your JSON file with { } couple (add { to at beginning and } to end). It should resolve the issue.

Related

string in correct json format but im still getting error while converting

im trying to convert data from json array to json object but I'm getting an error and I don't know why
java code here
void addToList(String json)
{
try
{
ja = new JSONArray(json);
for(int i = 0;i<ja.length();i++)
{
JSONObject item = ja.getJSONObject(i);
String sent = item.getString("#")+" x "+item.getString("name");
items.add(sent);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
itemlist.setAdapter(adapter);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
json = ["{"name":"fish","#":"1"}"]
and the error I'm getting is
org.json.JSONException: Value {"name":"fish","#":"1"} at 0 of type java.lang.String cannot be converted to JSONObject
This is the constructor of a JSONObject:
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
That means in your case specifically that json can't be an array. Try using something like:
json = "{"name":"fish","#":"1"}"

Appending jsonobject to an existing jsonobject

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

Finding erroneous Json object from json array

I have following type of JSON array (actually I received it as string so I'm trying to convert it to JSON array),
[{"Message":{"AccountId":"0","CreationDate":"02-DEC-16","Sbu":null,"ProfileId":"28261723","messageSeqId":69},"Offset":6},
{"Message":{"AccountId":"0","CreationDate":"02-DEC-16","Sbu":null,"ProfileId":"28261271","messageSeqId":76},"Offset":7},
{"Message":{"AccountId":"0","CreationDate":"06-DEC-16","Sbu":null,"ProfileId":"28261871","messageSeqId":99},"Offset":8},
{"Message":{"AccountId":"0","CreationDate":"06-DEC-16","Sbu":null,"ProfileId":"28261921","messageSeqId":101},"Offset":9},
{"Message":{"AccountId":"0","CreationDate":"07-DEC-16","Sbu":null,"ProfileId":"28260905","messageSeqId":105},"Offset":10}]
Sometimes this JSON array parsing fails because one JSON objects has fails to parse (I'm using JSON.simple to the JSON parsing). Is there a way to identify the erroneous JSON object?
Here is the code part(ResponseJson is above string that want to convert to JSON array),
JSONParser jsonParser = new JSONParser();
try{
JSONArray jsonArray = (JSONArray) jsonParser.parse(ResponseJson);
int jsonArrayLength = jsonArray.size();
System.out.println("jsonArray length: " + jsonArrayLength);
if (jsonArrayLength > 0) {
subscribeMessageEvent(topic,qStart,jsonArrayLength,jsonArray);
}
}catch (Exception e){
e.printStackTrace();
}
No, you can't identify which JSON Object is not properly formed with your current implementation.
Anyways, if you're receiving your input as a String, you could split it into the different messages and then parse them separately. That way you're in control and you can decide what to do with them individually.

how to read JSON from HTTP GET request?

I have created a java server which gets HTTP GET request url as
/Star/getDetails?sentMsg=data.requestorName:ABC,data.companyName:EFG,portfolios:
[{name:,placeholder:Portfolio 1,positions:[{ticker:T1234,weight:29.85},
{ticker:T2345,weight:70.15}],active:false}],analyticsDate:20140630}
I have to parse sentMsg parameter such as I am able to read each variable individually. For eg, i should be able to read data.requestorName, companyName. I am not able to find a way to do it.
request.getParameter("sentMsg") always return String.
Tried parsing it through json-simple
JSONParser jp = new JSONParser();
try {
Object obj = jp.parse(sentMsg);
JSONArray ja = (JSONArray)obj;
} catch (ParseException e) {
e.printStackTrace();
}
But this gives parse exception. I have limitation to use json-simple jar only. Any suggestion on how to do it?
Get the paramter sentMsg from HttpRequest object store it into a string. Split from comma i.e. "," and the last second token would be the json string. You can now parse it using Json simple lib and extract values from it.
Provided you have valid JSON like:
private static String jsonString = "[{name : \"stackOverFlow\"}]";
Convert it to JSONArray like:
JSONArray jsonArray = new JSONArray(jsonString );
Then you can get value out of JSONArray by looping through it:
for (int i = 0; i < jsonArray.length(); i++) { //Iterating over mediaArray
JSONObject media = jsonArray.getJSONObject(i);
String nameFromJSON = media.getString("name");
System.out.println("Name = " + nameFromJSON);
}
Output will be:
//Name = stackOverFlow

Gson.fromJson() - throw Exception if Type is different

I've created REST service which returns ExceptionEntity serialized class as a result if something gone wrong.
I want to throw some exception if json which should be deserialized by Gson.fromJson() is in different type. For example I've got this string which should be deserialized (my.ExceptionEntity.class):
{"exceptionId":2,"message":"Room aaaa already exists."}
but I use Room class as type for this serialized string:
String json = "{\"exceptionId\":2,\"message\":\"Room aaaa already exists.\"}";
Room r = gson.fromJson(json, Room.class);
// as a result r==null but I want to throw Exception; how?
[EDIT]
I've tested this and it doesn't work:
try {
return g.fromJson(roomJson, new TypeToken<Room>(){}.getType());
// this also doesn't work
// return g.fromJson(roomJson, Room.class);
} catch (JsonSyntaxException e) {
pepuch.multiplayergame.entity.Exception ex = g.fromJson(roomJson, pepuch.multiplayergame.entity.Exception.class);
throw ExceptionController.toGameServerException(ex);
} catch (JsonParseException e) {
pepuch.multiplayergame.entity.Exception ex = g.fromJson(roomJson, pepuch.multiplayergame.entity.Exception.class);
throw ExceptionController.toGameServerException(ex);
}
According to GSon documentation an exception is already thrown if the json stream can't be deserialized according to the type you provided:
Throws:
JsonParseException - if json is not a valid representation for an object of type classOfT
But this is an unchecked exception, if you want to provide a custom exception you should try with
try {
Room r = gson.fromJson(json, Room.class);
}
catch (JsonParseException e) {
throw new YourException();
}
try to convert it to Json first then convert it to the object type you want.
val newJson = Gson().toJson(json)
val r = gson.fromJson(json, Room.class)

Categories