0

I am new to java and android development. I am learning json parsing. I got json response something like this.

{"code":"0","data":    
[ {"chrDesigName":"Developer","chrempName":"Test Employee1"},
  {"chrDesigName":"Developer","chrempName":"Test Employee2"}, 
  {"chrDesigName":"Tester","chrempName":"Test Employee3"},
  {"chrDesigName":"Analyst","chrempName":"Test Employee4"},
  {"chrDesigName":"Developer","chrempName":"Test Employee5"},
  {"chrDesigName":"Tester","chrempName":"Test Employee6"}]

I want to parse this Json into something like this.

{"Developer" : [{"chrempName" : "Test Employee1"},
                    {"chrempName" : "Test Employee2"},
                    {"chrempName" : "Test Employee5"}],
"Tester" : [{"chrempName" : "Test Employee3"},
                    {"chrempName" : "Test Employee6"}],
"Analyst" : [{"chrempName" : "Test Employee4"}]}  

How can I acheive this? My motive is to group all the employees according to their designations.

5 Answers 5

4

As a quick hack , i have used 2 different libraries to do it. You can "uniformize" using Jackson as well.

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class JsonReformatter {

    public static void main(String[] args) throws Exception {
        String jsonString = "{\"code\": \"0\",\"data\": [{\"chrDesigName\": \"Developer\",\"chrempName\": \"Test Employee1\"},{\"chrDesigName\": \"Developer\",\"chrempName\": \"Test Employee2\"},{\"chrDesigName\": \"Tester\",\"chrempName\": \"Test Employee3\"},{\"chrDesigName\": \"Analyst\",\"chrempName\": \"Test Employee4\"},{\"chrDesigName\": \"Developer\",\"chrempName\": \"Test Employee5\"},{\"chrDesigName\": \"Tester\",\"chrempName\": \"Test Employee6\"}]}";

        ObjectMapper mapper = new ObjectMapper();

        // Map<String, Object> dataMap = mapper.readValue(jsonString,
        // new TypeReference<Map<String, Object>>() {
        // });
        //
        // System.out.println(dataMap.get("data") +
        // ((ArrayList)dataMap.get("data")).get(0).getClass().getName()) ;

        JsonArray dataArray = new JsonParser().parse(jsonString).getAsJsonObject().getAsJsonArray("data");

        HashMap<String, List<String>> designationsMap = new HashMap<String, List<String>>();

        for (JsonElement element : dataArray) {
            String designation = element.getAsJsonObject().get("chrDesigName").getAsString();
            String empName = element.getAsJsonObject().get("chrempName").getAsString();
            if (designationsMap.containsKey(designation)) {
                designationsMap.get(designation).add(empName);
            } else {
                ArrayList<String> emptyList = new ArrayList<String>();
                emptyList.add(empName);
                designationsMap.put(designation, emptyList);
            }
        }

        StringWriter result = new StringWriter();
        mapper.writeValue(result, designationsMap);
        System.out.println(result);

    }

}

This prints

{"Analyst":["Test Employee4"],"Tester":["Test Employee3","Test Employee6"],"Developer":["Test Employee1","Test Employee2","Test Employee5"]}

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.1</version>
</dependency>

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.7</version>
</dependency>
Sign up to request clarification or add additional context in comments.

9 Comments

How did you import those two libraries? I tried "compile 'com.fasterxml.jackson.core:jackson-core:2.7.3' compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.3' compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3' compile 'com.google.code.gson:gson:2.2.4'" in gradle and also added "jackson-mapper-lgpl-1.2.1.jar" in library. Getting " error: cannot access ObjectCodec class file for org.codehaus.jackson.ObjectCodec not found" , cannot resolve symbol objectmapper & cannot resolve method writevalue
Added dependencies that I used in Maven. If you add jars manually , it may prove difficult as at runtime you may get ClassNotFound exception
Fine. I am now getting only unhandled exception for mapper.writefile
Can you tell the full stacktrace and the error you get. Also if the answer works please do accept the answer as accepted :)
Error:(16, 32) error: package org.codehaus.jackson.map does not exist, Error:(28, 32) error: package org.codehaus.jackson.map does not exist, Error:(52, 9) error: cannot find symbol class ObjectMapper, Error:(52, 35) error: cannot find symbol class ObjectMapper, Error:(85, 16) error: cannot find symbol class JsonMappingException
|
1

Here is the code:

JsonParser parser =  new JsonParser();

JsonElement jsonElement = parser.parse(json);
JsonObject jsonObj = jsonElement.getAsJsonObject();

JsonArray data = new JsonArray();
data = jsonObj.getAsJsonArray("data");

JsonArray developer = new JsonArray();
JsonArray tester = new JsonArray();
JsonArray analyst = new JsonArray();

for (int i=0; i < data.size; i++){
JsonObject itemArr = (JsonObject)data.get(i);
JsonObject temp = new JsonObject();

if(itemArr.get("chrDesigName").getAsString().equals("Developer")){
   temp.addProperty("chrempName",itemArr.get("chrempName").getAsString());
   developer.add(temp);
}else if(itemArr.get("chrDesigName").getAsString().equals("Tester")){
   temp.addProperty("chrempName",itemArr.get("chrempName").getAsString());
   tester.add(temp);
}else if(itemArr.get("chrDesigName").getAsString().equals("Analyst")){
   temp.addProperty("chrempName",itemArr.get("chrempName").getAsString());
   analyst.add(temp);
}
}

JsonObject resultObject = new JsonObject();
resultObject.add("Developer",developer);
resultObject.add("Tester",tester);
resultObject.add("Analyst",analyst);

This way you can make a new resultObject object according to your need. This is a static way. You can take it to dynamic way further. You will need to add com.google.gson library to compile this code.

1 Comment

I dont know how many designations will be there or what all designations are. So I will have to do this in dynamic way. Can you help with that?
1

You can simply achieve this by: first storing all the 'chrDesigName' value in an array and then loop through each element of this array to create your desired JSON object.

e.g. //using JSON.simple module for decode/encode into JSON object.
JSONObject obj1 = {"code":"0","data":    
[ {"chrDesigName":"Developer","chrempName":"Test Employee1"},
  {"chrDesigName":"Developer","chrempName":"Test Employee2"}, 
  {"chrDesigName":"Tester","chrempName":"Test Employee3"},
  {"chrDesigName":"Analyst","chrempName":"Test Employee4"},
  {"chrDesigName":"Developer","chrempName":"Test Employee5"},
  {"chrDesigName":"Tester","chrempName":"Test Employee6"}]};

//Now, store all 'chrDesigName' in a local arrray.
List<String> arr = new ArrayList<String>();
for(JSONObject json : obj1.get("data")){
   //avoid to add duplicate entry. e.g. there are multiple Developer so avoid adding more than 1 times.
   boolean isDuplicate = false; 
   for(int i=0; i<arr.size();i++){        
       if(arr[i]==json.get("chrDesigName")){
           isDuplicate = true;
       }
    }
    if(isDuplicate==false){
        arr.add(json.get("chrDesigName"));
    }
}

//Now finally create your desired parsed JSON object.
JSONObject result= new JSONObject(); //final Result JSON object.
for(String chrDesigName : arr){
    //first adding empty list.
    result.put(chrDesigName, new ArrayList<JSONObject>());

    //now, checking on each data obj1 if it has chrDesigName and if yes then getting its chrEmpName and adding in list.
    for(JSONObject json : obj1.get("data")){
        if(chrDesigName==json.get("chrDesigName"){
            JSONObject sub_json = new JSONObject();
            sub_json.put("chrempName",json.get("chrempName");
            result.get(chrDesigName).add(sub_json);
        }
    }    
}

1 Comment

Getting "cannot resolve method add(org.json.JSONObject)" on "result.get(chrDesigName).add(sub_json);"
0

Here is the code:

public class TestJSONGroup {
    public static void main(String[] args) throws ParseException {
        
        JSONParser parser = new JSONParser();
        String jsonString = "{\"code\":\"0\",\"data\":"
        + "[ {\"chrDesigName\":\"Developer\",\"chrempName\":\"Test Employee1\"},"
        + "  {\"chrDesigName\":\"Developer\",\"chrempName\":\"Test Employee2\"},"
        + "  {\"chrDesigName\":\"Tester\",\"chrempName\":\"Test Employee3\"},"
        + "  {\"chrDesigName\":\"Analyst\",\"chrempName\":\"Test Employee4\"},"
        + "  {\"chrDesigName\":\"Developer\",\"chrempName\":\"Test Employee5\"},"
        + "  {\"chrDesigName\":\"Tester\",\"chrempName\":\"Test Employee6\"}]}";
        
        //JSONObject obj1 =  (JSONObject) parser.parse( jsonString );
        JSONObject obj1 = new JSONObject(jsonString);

        //Now, store all 'chrDesigName' in a local arrray.
        List<String> arr = new ArrayList<String>();
        
        JSONArray json = obj1.getJSONArray("data");
        for (int j = 0; j < json.length(); j++) {
           //avoid to add duplicate entry. e.g. there are multiple Developer so avoid adding more than 1 times.
           boolean isDuplicate = false; 
           String chrDesigName = new String();
           for(int i=0; i<arr.size();i++){
               JSONObject jsonObject1 = json.getJSONObject(j);
               chrDesigName = jsonObject1.optString("chrDesigName"); 
               if(arr.get(i).equalsIgnoreCase(chrDesigName.trim())){
                   isDuplicate = true;
               }
            }
            if(isDuplicate==false){
                arr.add(chrDesigName);
            }
        }
        arr.remove(0);

        //Now finally create your desired parsed JSON object.
        JSONObject result= new JSONObject(); //final Result JSON object.
        for(String chrDesigName : arr){
            //first adding empty list.
            result.put(chrDesigName, new ArrayList<JSONObject>());
            //now, checking on each data obj1 if it has chrDesigName and if yes then getting its chrEmpName and adding in list.
            String chrDesigName2 = new String();
            JSONArray array = new JSONArray();
            for (int j = 0; j < json.length(); j++) {
                JSONObject jsonObject1 = json.getJSONObject(j);
                chrDesigName2 = jsonObject1.optString("chrDesigName");
                if(chrDesigName.equalsIgnoreCase(chrDesigName2.trim())){
                    JSONObject sub_json = new JSONObject();
                    sub_json.put("chrempName",json.get(j));
                    array.put(json.get(j));
                }
            } 
            result.put(chrDesigName, array);
        }
        System.out.println("result: "+ result.toString());
    }

and the result will be, just modify in some other

{
   "Analyst": [
      {
         "chrDesigName": "Analyst",
         "chrempName": "Test Employee4"
      }
   ],
   "Tester": [
      {
         "chrDesigName": "Tester",
         "chrempName": "Test Employee3"
      },
      {
         "chrDesigName": "Tester",
         "chrempName": "Test Employee6"
      }
   ],
   "Developer": [
      {
         "chrDesigName": "Developer",
         "chrempName": "Test Employee1"
      },
      {
         "chrDesigName": "Developer",
         "chrempName": "Test Employee2"
      },
      {
         "chrDesigName": "Developer",
         "chrempName": "Test Employee5"
      }
   ]
}

Comments

0

You can use JSON library such as Josson to do the transformation.

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(
    "{\"code\":\"0\",\"data\":" +
    "[ {\"chrDesigName\":\"Developer\",\"chrempName\":\"Test Employee1\"}," +
    "  {\"chrDesigName\":\"Developer\",\"chrempName\":\"Test Employee2\"}, " +
    "  {\"chrDesigName\":\"Tester\",\"chrempName\":\"Test Employee3\"}," +
    "  {\"chrDesigName\":\"Analyst\",\"chrempName\":\"Test Employee4\"}," +
    "  {\"chrDesigName\":\"Developer\",\"chrempName\":\"Test Employee5\"}," +
    "  {\"chrDesigName\":\"Tester\",\"chrempName\":\"Test Employee6\"}]" +
    "}");
JsonNode node = josson.getNode(
    "data.group(chrDesigName).map(chrDesigName::elements.map(chrempName)).mergeObjects()");
System.out.println(node.toPrettyString());

Output

{
  "Developer" : [ {
    "chrempName" : "Test Employee1"
  }, {
    "chrempName" : "Test Employee2"
  }, {
    "chrempName" : "Test Employee5"
  } ],
  "Tester" : [ {
    "chrempName" : "Test Employee3"
  }, {
    "chrempName" : "Test Employee6"
  } ],
  "Analyst" : [ {
    "chrempName" : "Test Employee4"
  } ]
}

Comments

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.