首页 > 解决方案 > JSON 展平器仅将 JSON 中的最后一个对象返回到展平形式

问题描述

我有一个如下所示的 JSON,

 {
  "users": [
    {
      "displayName": "Sharad Dutta",
      "givenName": "",
      "surname": "",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "emailAddress",
          "issuerAssignedId": "kkr007@gmail.com"
        }
      ],
      "extension_timezone": "VET",
      "extension_locale": "en-GB",
      "extension_tenant": "EG12345"
    },   
    {
      "displayName": "Sharad Dutta",
      "givenName": "",
      "surname": "",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "emailAddress",
          "issuerAssignedId": "kkr007@gmail.com"
        }
      ],
      "extension_timezone": "VET",
      "extension_locale": "en-GB",
      "extension_tenant": "EG12345"
    }
  ]
}

我有上面的代码,它能够像这样展平 JSON,

{
  "extension_timezone": "VET",
  "extension_tenant": "EG12345",
  "extension_locale": "en-GB",
  "signInType": "userName",
  "displayName": "Wayne Rooney",
  "surname": "Rooney",
  "givenName": "Wayne",
  "issuerAssignedId": "pdhongade007",
  "extension_user_type": "user"
}

但是代码只返回 JSON 的“用户”数组中的最后一个用户。它不会返回第一个用户(基本上只有最后一个用户,无论有多少用户),只是最后一个用户以扁平形式从“用户”数组中出来。

public class TestConvertor {
    
    static String userJsonAsString;
    public static void main(String[] args) throws JSONException {
        
        String userJsonFile = "C:\\Users\\Administrator\\Desktop\\jsonRes\\json_format_user_data_input_file.json";
                
                try {
                    userJsonAsString = readFileAsAString(userJsonFile);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
        
        
        JSONObject object = new JSONObject(userJsonAsString); // this is your input
        Map<String, Object> flatKeyValue = new HashMap<String, Object>();
        System.out.println("flatKeyValue : " + flatKeyValue);
        readValues(object, flatKeyValue);
        System.out.println(new JSONObject(flatKeyValue)); // this is flat
    }

    static void readValues(JSONObject object, Map<String, Object> json) throws JSONException {
        for (Iterator it = object.keys(); it.hasNext(); ) {
            String key = (String) it.next();
            Object next = object.get(key);
            readValue(json, key, next);
        }
    }

    static void readValue(Map<String, Object> json, String key, Object next) throws JSONException {
        if (next instanceof JSONArray) {
            JSONArray array = (JSONArray) next;
            for (int i = 0; i < array.length(); ++i) {
                readValue(json, key, array.opt(i));
                
            }
        } else if (next instanceof JSONObject) {
            readValues((JSONObject) next, json);
        } else {
            json.put(key, next);
        }
    }
    private static String readFileAsAString(String inputJsonFile) throws Exception {
            
            return new String(Files.readAllBytes(Paths.get(inputJsonFile)));
    }
}

请建议我在哪里做错了或者我的代码需要修改。

标签: javaarraysjsoncollections

解决方案


请尝试以下方法,这将为您提供用户和标识符(平面文件本身)的逗号分隔格式,

 public static void main(String[] args) throws JSONException, ParseException {
    
            String userJsonFile = "path to your JSON";
            final StringBuilder sBuild = new StringBuilder();
            final StringBuilder sBuild2 = new StringBuilder();
            
            try {
                String userJsonAsString = convert your JSON to string and store in var;
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            JSONParser jsonParser = new JSONParser();
            JSONObject output = (JSONObject) jsonParser.parse(userJsonAsString);
            try {
                
                JSONArray docs = (JSONArray) output.get("users");
                Iterator<Object> iterator = docs.iterator();
                
                
                while (iterator.hasNext()) {
                    JSONObject userEleObj = (JSONObject)iterator.next();
                    JSONArray nestedIdArray = (JSONArray) userEleObj.get("identities");
                    Iterator<Object> nestIter = nestedIdArray.iterator();
                     
                    while (nestIter.hasNext()) {
                        JSONObject identityEleObj = (JSONObject)nestIter.next(); 
                        identityEleObj.keySet().stream().forEach(key -> sBuild2.append(identityEleObj.get(key) + ","));
                        userEleObj.keySet().stream().forEach(key -> {
                            if (StringUtils.equals((CharSequence) key, "identities")) {
                                sBuild.append(sBuild2.toString());
                                sBuild2.replace(0, sBuild2.length(), "");
                            } else {
                                sBuild.append(userEleObj.get(key) + ","); 
                            }
                                
                        });
                         
                    }
                    sBuild.replace(sBuild.lastIndexOf(","), sBuild.length(), "\n");  
                }
                
                System.out.println(sBuild);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

推荐阅读