簡體   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