繁体   English   中英

如何获取Json对象中的详细信息?

[英]How to get the details in a Json object?

我想知道如何从Json Object获取更多细节。

这是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中的Square,Rectangle等属性每个都是具有自己属性的JSONObjects。 要访问这些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"));

顺便说一句,如果要具有重复的键(例如,多个Square),则需要将数据表示为数组(或列表)与地图,并使形状类型成为形状详细信息(长度,宽度等)的属性。

  [
   { "shape": "Square", 
     "Length": 6
   },
   { "shape": "Square", 
     "Length": 10
   }
  ]

暂无
暂无

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

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