使用嵌套Json进行对象映射的最佳方法

问题描述 投票:1回答:1

[目前,我正在尝试编写一个使用Feign和Spring与公共API进行交互的网站。我在决定如何处理深度嵌套JSON的对象映射时遇到麻烦。

Ex:

[
  {
    "type": "console",
    "category": "Console",
    "result_count": 1,
    "shown_count": 1,
    "result": [
      {
        "name": "Nintendo Switch",
        "id": "nintendo-switch",
        "platform": {
          "name": "Nintendo",
          "category": "nintendo",
          "type": "platform"
        },
        "image": {
          "url": "https://encrypted-tbn1.gstatic.com/shopping?q=tbn:ANd9GcRqJYIheMDjTE9WAHjMSW4bjh7OplS7Bep9CdsBBLWMwGdXim7xOG4&usqp=CAc",
          "height": 409,
          "width": 631
        },
        "min_price": 205,
        "variations": [
          {
            "items": [
              {
                "hex_code": "#696969",
                "name": "Gray",
                "id": "space-gray",
                "type": "color"
              },
              {
                "hex_code": "#C0C0C0",
                "name": "Silver",
                "id": "silver",
                "type": "color"
              }
            ],
            "name": "Color",
            "type": "color"
          },
          {
            "items": [
              {
                "name": "Nintendo",
                "id": "nintendo",
                "type": "platform"
              }
            ],
            "name": "Platform",
            "type": "platform"
          }
        ]
      }
    ]
  }
]

到目前为止,我只有一个Java文件,其中包含JSON中每个对象的类,并且我已经考虑过让Object映射器将所有内容都放入HashMap中。有没有更优雅的方法可以做到这一点?

public class SearchResults {
    private List<SearchResult> products;
    private int resultCount;
    private String type;

}

class SearchResult {
    private String name;
    private String slug;
    private Image image;

}

class Image {
    private String URL;
    private String height;
    private String width;

}
java dto spring-cloud-feign
1个回答
0
投票

基于提供的json文件,我设计了类,还提供了将json文件解析为java的代码

public class  Console{
     String type;
     String category;
     int result_count;
     int show_count;
     Result [] result;
}

public class Result{
    String name;
    String id;
    Platform platform;
    Image image;
    int mini_price;
    Variation [] variations;
}

public class Platform{
    String name;
    String category;
    String type;
}

public class Image{
    String url;
    int height;
    int width;
}

public class Variation{
    String name;
    String type;
    Item [] items;

}

public class Item{
    String hex_code;
    String name;
    String id;
    String type;
}

要解析的代码:

ObjectMapper objectMapper = new ObjectMapper();
         objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
         Console[] consoles = objectMapper.readValue(ResourceUtils.getFile("path of json file"), Console[].class);
         logger.info("Continents -> {}",(Object)continents);
         for(Console console:consoles) {
            //read the data accordingly
                     }
© www.soinside.com 2019 - 2024. All rights reserved.