在java - android studio中使用键对Json响应进行分组

xdyibdwo  于 2023-02-19  发布在  Android
关注(0)|答案(5)|浏览(166)

我是java和android开发的新手。我正在学习json解析。我得到了类似这样的json响应。

{"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"}]

我想把这个Json解析成这样。

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

我怎样才能做到这一点呢?我的动机是根据所有员工的职务将他们分组。

wxclj1h5

wxclj1h51#

作为一个快速的黑客,我已经使用了2个不同的库来做到这一点。你可以“统一”使用Jackson以及。

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);

    }

}

这个打印
一个月一个月一个月一个月一个月

<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>
vsaztqbk

vsaztqbk2#

代码如下:

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);

这样你就可以根据你的需要创建一个新的resultObject对象。这是一个静态的方法。你可以进一步把它变成动态的方法。你需要添加com.google.gson库来编译这个代码。

am46iovg

am46iovg3#

您可以通过以下方式简单地实现这一点:首先将所有'chrDesigName'值存储在一个数组中,然后循环遍历该数组的每个元素以创建所需的JSON对象。

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);
        }
    }    
}
4uqofj5v

4uqofj5v4#

下面是代码:

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());
    }

结果就是,只需要修改一些其他的

{
   "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"
      }
   ]
}
kgqe7b3p

kgqe7b3p5#

您可以使用JSON库(如 Josson)进行转换。
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());

产出

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

相关问题