我想知道如何从 Json 对象获取更多详细信息。
这是 Json 文件:
{
"Shapes": "Models",
"Square": {
"Length": 10
},
"Rectangle": {
"Length": 10,
"Width": 20
},
"Circle": {
"Radius": 5
},
"Equilateral": {
"Side": 10
},
"Scalene": {
"Side1": 10,
"Side2": 5,
"Side3": 3
},
"Isosceles": {
"Side1": 10,
"Side2": 5,
"Side3": 5
}
}
我的代码如下:
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("filepath"));
JSONObject jsonObject = (JSONObject) obj;
Object Square = jsonObject.get("Square");
System.out.println("Square: " + Square);
Object Rect = jsonObject.get("Rectangle");
System.out.println("Rectangle: " + Rect);
}
o/p 就像
Square: {"Length":10}
Rectangle: {"Length":10,"Width":20}
我想获得更多详细信息,例如“长度/宽度/半径”
最佳答案
示例 JSON 中的正方形、矩形等属性都是具有自己属性的 JSONObject。要访问这些 JSON 对象的属性,请将 Object 转换为 JSONObject 实例以访问其方法。
(JSONObject) Square = (JSONObject)jsonObject.get("Square");
System.out.println("Square: " + Square);
System.out.println("Square: Length=" + Square.get("Length"));
JSONObject rect = (JSONObject)jsonObject.get("Rectangle");
System.out.println("Rectangle: " + rect);
System.out.printf("Rectangle: Length=%s Width=%s%n",
rect.get("Length"), rect.get("Width"));
顺便说一句,如果想要有重复的键(例如多个方 block ),那么您需要将数据表示为数组(或列表)而不是 map ,并使形状类型成为形状详细信息(长度、宽度等)的属性。
[
{ "shape": "Square",
"Length": 6
},
{ "shape": "Square",
"Length": 10
}
]
关于java - 如何获取 Json 对象中的详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32426252/