简体   繁体   中英

parse Json to Map<String,String>

I have Json response like :

[
 {       
   "first_name": "fname1",
   "last_name": "lname1"
 },
 {
   "first_name": "fname2",
   "last_name": "lname2",
   "city_name": "paris"
 },
 {
   "first_name": "fname2",
   "last_name": "lname2",
   "city_name": "paris",
   "Address": "1st Ave"
 }
 .
 .
 .
]

and my fields in JsonObject is dynamic so i can't use a class with predefined fields , so i've decided to use Map to parse the Json response as below :

Collection<List<Map<String,String>>> list_Objects = null;
Reader reader = new InputStreamReader(is);
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<List<Map<String,String>>>>(){}.getType();
list_objects = gson.fromJson(reader, collectionType);

but it throws me this error :

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1

im not expert in Json parsing so please tell me where is my mistake or if there is another way to implement such behavior i would be very appreciated.

I think the problem is with your Collection wrapper on the List one.

You just need to define the list_Objects as List<Map<String, String>> .

I just tried the following with Jackson's ObjectMapper (which should work the same as GSON) and it worked ok:

List<Map<String, String>> list_objects = objectMapper.readValue(jsonString, new TypeReference<List<Map<String, String>>>(){});

The result is a List of LinkedHashMap objects.

For your GSON example, you just need to remove the Collection<> , or the List<> if you prefer.

If I'm reading this correctly, you're defining your list twice.

Collection<List<Map<String, String>>> would map to a structure like

[ [ {"bla": "bla"}, {"bla": "bla"} ], [ {"foo": "bar"}, ... ], ... ]

(because List is a kind of Collection). So, try using List<Map<String, String>> and see if that works...

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