1

I'm new to java. Could you please help me in parsing the below json in java. I have a json which contains a list of empid's and for each empid there will be couple of dept id's.

Please see the below format

empid  deptid
1       111
1       222
1       333
2       123
2       111

So I will have the data in json as above format. And I need parse this json in java and I need to store this data into a map.

Like Map<String,List<String>> where key will be the empid and the value will be dept id's.

So please help me with this.

Note : I will get input as Json Object from client. I need to parse this json object in java.

Json Representation :

  {"employees":[
   {"empid":"1","deptid":["111","222","333"]},
   {"empid":"2","deptid":["123","111"]},
]}

Thanks.

5
  • That format isn't JSON. Could you post what the actual JSON will look like? Commented Jun 1, 2016 at 13:31
  • I don't have the real Json representation , that's the reason I given in the table format Commented Jun 1, 2016 at 13:32
  • Json will look something like this. { [ "empid" : "1", "deptid" : ["111","222","333"] ], [ "empid" : "2", "deptid" : ["123","111"] ] } Commented Jun 1, 2016 at 13:39
  • @Naresh - "Something like" .... That isn't valid JSON. Step 1 - read the JSON syntax graphs on json.org. Step 2 - look at all of the JSON libraries for Java, as listed on the same site. Commented Jun 1, 2016 at 14:20
  • This is the actual json representation : {"employees":[ {"empid":"1","deptid":["111","222","333"]}, {"empid":"2","deptid":["123","111"]}, ]} Commented Jun 1, 2016 at 14:41

1 Answer 1

1

Use gson library https://github.com/google/gson

use typetoken to parse json string to java object

Gson gson = new Gson();
Type type = new TypeToken<Map<String,List<String>>>(){}.getType();
Map<String,List<String>> obj = gson.fromJson(jsonData, type );
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry to ask this . I'm a beginner just learning the things. Instead of using Gson, can't we use simple core java to store the data in map from json.
I am not aware of any core java library for JSON to Java and vice-versa. I mainly use GSON and JACKSON library to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.