[英]Flattening multidimensional JSON in JAVA
I have a JSON which looks like this,我有一个看起来像这样的 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"
}
]
}
I am writing a Java code where I am parsing this Multidimensional JSON to FLAT JSON.我正在编写一个 Java 代码,我将这个多维 JSON 解析为 FLAT JSON。 If you look closely, the JSON is wrapped in a "users" wrapper and then has couple of users as objects.如果仔细观察,JSON 被包装在“用户”包装器中,然后有几个用户作为对象。 For each user, there is a field called "identifiers" which is again a wrapper.对于每个用户,都有一个称为“标识符”的字段,它也是一个包装器。
I want to flat this JSON, I have written a code but it is leaving a JSON blob for identifiers, for non nested it is working fine我想把这个 JSON 弄平,我写了一个代码,但它为标识符留下了一个 JSON blob,对于非嵌套它工作正常
JSONObject output;
try {
output = new JSONObject(userJsonAsString);
JSONArray docs = output.getJSONArray("users");
System.out.println(docs);
This is giving me below output, however i still have to flat inner wrapper "identifiers"这给了我下面的输出,但是我仍然必须平整内部包装器“标识符”
[
{
"extension_timezone": "VET",
"extension_tenant": "EG12345",
"extension_locale": "en-GB",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "pdhongade007@gmail.com"
}
],
"displayName": "Sharad Dutta",
"surname": "",
"givenName": "",
"extension_user_type": "user"
},
{
"extension_timezone": "VET",
"extension_tenant": "EG12345",
"extension_locale": "en-GB",
"identities": [
{
"signInType": "userName",
"issuerAssignedId": "pdhongade007"
}
],
"displayName": "Wayne Rooney",
"surname": "Rooney",
"givenName": "Wayne",
"extension_user_type": "user"
}
]
This is what I need,这就是我需要的
{
"extension_timezone": "VET",
"extension_tenant": "EG12345",
"extension_locale": "en-GB",
"signInType": "emailAddress",
"issuerAssignedId": "pdhongade007@gmail.com",
"displayName": "Sharad Dutta",
"surname": "",
"givenName": "",
"extension_user_type": "user"
}
I have to then parse this to CSV, which I know how, I just need to flat this further.然后我必须将它解析为 CSV,我知道如何,我只需要进一步扁平化。 Any help will be appreciated.任何帮助将不胜感激。 I tried looking around, but a lot of them were using external dependencies.我试着环顾四周,但其中很多都在使用外部依赖项。
//UPDATE //更新
{
"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"
}
When I tried @Jakub solution, I am getting the flat JSON, however it is not iterating for all the users.当我尝试@Jakub 解决方案时,我得到了平面 JSON,但它并没有为所有用户迭代。 Just one!(I am guessing the last user only)只有一个!(我猜只有最后一个用户)
You can traverse the json and just store the "leafs" in map.您可以遍历 json 并将“叶子”存储在地图中。 Note: array of primitives will turn into the last value in the array with this approach, but that's what you described :)注意:使用这种方法,原始数组将变成数组中的最后一个值,但这就是您所描述的:)
Something like this:像这样的东西:
void flatJson() throws JSONException {
JSONObject object = new JSONObject(userJsonAsString); // this is your input
Map<String, Object> flatKeyValue = new HashMap<>();
readValues(object, flatKeyValue);
System.out.println(new JSONObject(flatKeyValue)); // this is flat
}
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);
}
}
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);
}
}
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 = "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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.