简体   繁体   中英

Decoding JSON String for List with names

I am try to decode a JSON string as below

{
   "id_value": [
    {
        "id": "1.1.1.1",
        "value": "v1"
    },
    {
        "id": "1.1.1.2",
        "value": "v2"
    }
   ]
}

Which is basically a list of id_value object. IdValue is a POJO class with a string variable of id and value.

I am able to decode the JSON string , when I passed in JSON without the list name , as below.

  [
  {
    "id": "1.1.1.1",
    "value": "v1"
  },
  {
    "id": "1.1.1.2",
    "value": "v2"
  }
]

My JAVA code is as below :

String jsonString1 = "{\"id_value\": [{\"id\": \"1.1.1.1\",\"value\": \"v1\"},{\"id\": \"1.1.1.2\",\"value\": \"v2\"}]}";
String jsonString2 = "[{\"id\": \"1.1.1.1\",\"value\": \"v1\"},{\"id\": \"1.1.1.2\",\"value\": \"v2\"}]";

List<IdValue> idValues = null;
try {
   Gson gson = new Gson();
   idValues = gson.fromJson(jsonString2, new TypeToken<List<IdValue>>(){}.getType());         
}
catch (Exception e) {
   e.printStackTrace();
}
System.out.println(idValues);

My code works well with jsonString2 , but I am getting the below exception with jsonString1. Both of them are lists , but why it is failing for one and working for other.

com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@67ac19 failed to deserialize json object {"id_value":[{"id":"1.1.1.1","value":"v1"},{"id":"1.1.1.2","value":"v2"}]} given the type java.util.List<com.something.json.IdValue>

Any inputs would be helpful.

Thanks !!

id_value isn't part of your IdValue POJO. So the TypeToken of List does not know how to map the id_value piece of the JSON string.

jsonString2 represents a List<IdValue>

jsonString1 represents a Map<String, List<IdValue>>

So, to process jsonString1 you need:

Map<String, List<IdValue>> map = gson.fromJson(json, new TypeToken<Map<String, List<IdValue>>>(){}.getType());
List<idValue> idValues = map.get("id_value");

Here is more general way to get your IdValues from jsonString1 even if there are another entries in it:

Gson gson = new Gson();
JsonParser parser = new JsonParser();
String jsonString1 = "{\"id_value\": [{\"id\": \"1.1.1.1\",\"value\": \"v1\"},{\"id\": \"1.1.1.2\",\"value\": \"v2\"}]}";
JsonElement e = parser.parse(jsonString1);
JsonArray idValueArray = e.getAsJsonObject().getAsJsonArray("id_value");
List<IdValue> idValues = gson.fromJson(idValueArray, new TypeToken<List<IdValue>>(){}.getType());

Because jsonString1's deserializing type is not same with jsonString2's. If you want to use same deserializing type, you should first do substring.

jsonString1 = jsonString1.substring(s.indexOf("["));
jsonString1 = jsonString1.substring(0, s.lastIndexOf("]") + 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM