Niru... Niru... - 11 days ago 5
JSON Question

Json and java conversion

Below is piece of my java code

Type relMapType = new TypeToken<Map<String, Map<String, Map<String ,Map<String, List<Set<ProfileData>>>>>>>(){}.getType();
InputStream is = new FileInputStream("D:\\work.json");
String jsonTxt;
try {
jsonTxt = IOUtils.toString(is);
System.out.println(jsonTxt);
JSONObject jsons = new JSONObject(jsonTxt);
String jString= gson.toJson(jsons);
gson.fromJson(jString, relMapType);
} catch (IOException e) {
e.printStackTrace();
}


Below is my json data in "work.json" file

{
"string1":{
"string2":{
"string3":{
"string4":[
{
"primaryKey":{
"projectCode":"PC",
"type":"type1",
"code1":"data1",
"code2":"data2"
},
"status":"status1",
"Id":"123",
"frequency":"freq",
"destFre":"destFreq"
}
]
}
}
}
}


when I run the code getting below exception. Can anyone help me?

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 5 column 21
at com.google.gson.Gson.fromJson(Gson.java:806)
at com.google.gson.Gson.fromJson(Gson.java:761)
at com.google.gson.Gson.fromJson(Gson.java:710)
at com.JsonExample.main(JsonExample.java:97)


Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 5 column 21

Answer

You are using a Set within a List in List<Set<ProfileData>>. Both are Collections and will therefore be treated as arrays. The same part of your JSON is an array of objects. Remove Set or List and it should work.