【问题标题】:JSON flattener returning only last object from JSON to a flattened formJSON 展平器仅将 JSON 中的最后一个对象返回到展平形式
【发布时间】:2021-01-06 02:46:27
【问题描述】:

我有一个如下所示的 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)));
    }
}

请提出我哪里做错了或者我的代码需要修改。

【问题讨论】:

  • 您的 JSON 不正确。使用它来检查它并使用有效的 JSON jsonformatter.curiousconcept.com/# 更新您的问题
  • 那个 JSON 有什么不正确的地方吗?你能给我解释一下吗?因为它是一个包裹在数组“users”中的多维 JSON。
  • 您检查过我在评论中添加的链接吗?它指出 JSON 缺少对象的右括号和数组的右括号。除此之外,您为什么要以这种方式存储用户?您可以创建一个名为 users 的数组并在其中存储多个用户对象。
  • 对不起,我没有意识到我错过了 JSON,是的,你是对的,JSON 是错误的,我会更新答案。
  • 我已经修复了 JSON,我的错误。

标签: java arrays json collections


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 2013-10-06
    • 2019-05-25
    • 2020-03-02
    • 2019-01-17
    • 1970-01-01
    • 2021-10-19
    • 2012-05-29
    相关资源
    最近更新 更多