JSON扁平化程序仅返回JSON中的最后一个对象,以扁平化的形式返回。

huangapple go评论67阅读模式
英文:

JSON flattener returning only last object from JSON to a flattened form

问题

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

        JSONArray usersArray = new JSONObject(userJsonAsString).getJSONArray("users");
        JSONArray flattenedUsers = new JSONArray();

        for (int i = 0; i < usersArray.length(); i++) {
            JSONObject userObject = usersArray.getJSONObject(i);
            JSONObject flatUser = flattenUser(userObject);
            flattenedUsers.put(flatUser);
        }

        JSONObject resultObject = new JSONObject();
        resultObject.put("flattenedUsers", flattenedUsers);
        System.out.println(resultObject);
    }

    static JSONObject flattenUser(JSONObject user) throws JSONException {
        JSONObject flatUser = new JSONObject();
        
        for (Iterator<String> keys = user.keys(); keys.hasNext();) {
            String key = keys.next();
            Object value = user.get(key);
            
            if (value instanceof JSONObject) {
                JSONObject subObject = (JSONObject) value;
                JSONObject flattenedSubObject = flattenUser(subObject);
                for (Iterator<String> subKeys = flattenedSubObject.keys(); subKeys.hasNext();) {
                    String subKey = subKeys.next();
                    flatUser.put(subKey, flattenedSubObject.get(subKey));
                }
            } else if (value instanceof JSONArray) {
                JSONArray subArray = (JSONArray) value;
                for (int i = 0; i < subArray.length(); i++) {
                    if (subArray.get(i) instanceof JSONObject) {
                        JSONObject subArrayObj = subArray.getJSONObject(i);
                        JSONObject flattenedSubArrayObj = flattenUser(subArrayObj);
                        flatUser.putAll(flattenedSubArrayObj);
                    }
                }
            } else {
                flatUser.put(key, value);
            }
        }
        
        return flatUser;
    }

    private static String readFileAsAString(String inputJsonFile) throws Exception {
        return new String(Files.readAllBytes(Paths.get(inputJsonFile)));
    }
}

Please note that the provided code has been modified to achieve the desired result of flattening all users in the JSON array.

英文:

I have a JSON that looks like below,

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

I have the above code and it is able to flatten the JSON like this,

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

But the code is returning only the last user in the "users" array of JSON. It is not returning the first user (essentially the last user only, no matter how many users are there) just the last one is coming out in flattened form from the "users" array.

public class TestConvertor {
static String userJsonAsString;
public static void main(String[] args) throws JSONException {
String userJsonFile = &quot;C:\\Users\\Administrator\\Desktop\\jsonRes\\json_format_user_data_input_file.json&quot;;
try {
userJsonAsString = readFileAsAString(userJsonFile);
} catch (Exception e1) {
e1.printStackTrace();
}
JSONObject object = new JSONObject(userJsonAsString); // this is your input
Map&lt;String, Object&gt; flatKeyValue = new HashMap&lt;String, Object&gt;();
System.out.println(&quot;flatKeyValue : &quot; + flatKeyValue);
readValues(object, flatKeyValue);
System.out.println(new JSONObject(flatKeyValue)); // this is flat
}
static void readValues(JSONObject object, Map&lt;String, Object&gt; 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&lt;String, Object&gt; json, String key, Object next) throws JSONException {
if (next instanceof JSONArray) {
JSONArray array = (JSONArray) next;
for (int i = 0; i &lt; 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)));
}
}

Please suggest where I am doing wrong or my code needs modification.

答案1

得分: 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 = "将您的JSON转换为字符串并存储在变量中";
    } 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().forEach(key -> sBuild2.append(identityEleObj.get(key) + ","));
                userEleObj.keySet().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();
    }
}
英文:

Please try the below approach, this will give you a comma separated format for both user and identifier (flat file per se),

 public static void main(String[] args) throws JSONException, ParseException {
String userJsonFile = &quot;path to your JSON&quot;;
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(&quot;users&quot;);
Iterator&lt;Object&gt; iterator = docs.iterator();
while (iterator.hasNext()) {
JSONObject userEleObj = (JSONObject)iterator.next();
JSONArray nestedIdArray = (JSONArray) userEleObj.get(&quot;identities&quot;);
Iterator&lt;Object&gt; nestIter = nestedIdArray.iterator();
while (nestIter.hasNext()) {
JSONObject identityEleObj = (JSONObject)nestIter.next(); 
identityEleObj.keySet().stream().forEach(key -&gt; sBuild2.append(identityEleObj.get(key) + &quot;,&quot;));
userEleObj.keySet().stream().forEach(key -&gt; {
if (StringUtils.equals((CharSequence) key, &quot;identities&quot;)) {
sBuild.append(sBuild2.toString());
sBuild2.replace(0, sBuild2.length(), &quot;&quot;);
} else {
sBuild.append(userEleObj.get(key) + &quot;,&quot;); 
}
});
}
sBuild.replace(sBuild.lastIndexOf(&quot;,&quot;), sBuild.length(), &quot;\n&quot;);  
}
System.out.println(sBuild);
} catch (Exception e) {
e.printStackTrace();
}
}

huangapple
  • 本文由 发表于 2020年9月19日 19:01:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63967996.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定