简体   繁体   English

使用json-simple获取嵌套对象-父节点的通配符

[英]get nested Object using json-simple - Wildcard for parent Node

I want to retrieve "name" values and store them in an Arraylist from a JSON file in Java. 我想检索“名称”值并将其从Java中的JSON文件存储在Arraylist中。 I am using JSON-simple library Here is an example of my "file.json": 我正在使用JSON简单库这是“ file.json”的示例:

{
  "111": {

    "customer": {

        "name": "John Do",
        "Height": 5.9,
        "City": "NewYork"
    }

  },
  "222":{

    "customer": {

        "name": "Sean Williams",
        "Height": 6,
        "City": "Los Angeles"
    }
  }
}

Id numbers "111" and "222" are not significant for my program and they are randomly generated so I am not able to use jObject.get() as the values will constantly be changing. ID号“ 111”和“ 222”对我的程序而言并不重要,它们是随机生成的,因此我无法使用jObject.get()因为值将不断变化。 I tried searching for a wildcard for the parent Node and then go to child node customer and then name but haven't found such thing. 我尝试搜索父节点的通配符,然后转到子节点customer ,然后name但没有找到这样的东西。

Here is my code so far: 到目前为止,这是我的代码:

import java.io.*;
import java.util.ArrayList;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class npTest {

    public static void main(String[] args) throws IOException, ParseException {

        try {
            JSONParser jParser = new JSONParser();
            JSONObject jObject = (JSONObject) jParser.parse(new FileReader("file.json"));

//Notes

    } catch (FileNotFoundException e) {
        System.out.print("File not found!");
    }

}

} }

Notes: methods I have tried require jObject.get("id") . 注意:我尝试过的方法需要jObject.get("id") Also I noticed I am not able to store the JSONObject in another JSONObject, for example: JSONObject parentObj = new JSONObject(jObject.get("111")); 我还注意到我无法将JSONObject存储在另一个JSONObject中,例如: JSONObject parentObj = new JSONObject(jObject.get("111"));

You can iterate through the keys in a JSONObject using the keySet() method. 您可以使用keySet()方法遍历JSONObject的键。 Then pull out your "customer" and get their name. 然后拉出您的"customer"并获得他们的名字。

JSONParser jParser = new JSONParser();
JSONObject jObject = (JSONObject) jParser.parse(new FileReader("c:\\file.json"));

for(Object key : jObject.keySet()) {
    JSONObject customerWrapper = (JSONObject)jObject.get(key);
    JSONObject customer = (JSONObject)customerWrapper.get("customer");
    System.out.println(customer.get("name"));
}

JSONObject implements the Map interface. JSONObject实现Map接口。 So you could query for all map keys with normal Java syntax: 因此,您可以使用常规Java语法查询所有映射键:

for (Object innnerO : jObject.values()){
  JSONObject customerO = (JSONObject)((JSONObject)innerO).get("customer");
}

Note: This is written out of my head without compiler. 注意:这是在没有编译器的情况下写出来的。 So there might me errors. 所以可能有我的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM