简体   繁体   English

如何使用 spring 引导 api 调用提取嵌套的 json 值

[英]How to extract nested json values by using spring boot api call

I have the following json.我有以下 json。

[
    {
        "id": 1,
        "footwearList": [
            {
                "id": 1,
                "name": "sandals",
                "category": "men"
            },
            {
                "id": 3,
                "name": "sandals",
                "category": "women"
            }
        ],
        "clothingList": [
            {
                "id": 1,
                "name": "t-shirt",
                "category": "men"
            },
            {
                "id": 3,
                "name": "tshirt",
                "category": "women"
            }
        ]
    },
    {
        "id": 2,
        "footwearList": [
            {
                "id": 2,
                "name": "shoes",
                "category": "men"
            },
            {
                "id": 4,
                "name": "shoes",
                "category": "women"
            }
        ],
        "clothingList": [
            {
                "id": 2,
                "name": "shirt",
                "category": "men"
            },
            {
                "id": 4,
                "name": "shirt",
                "category": "women"
            }
        ]
    }
]

Fetched this json from api call from controller and wanted to fetch nested values like (footwearlist, clothinglist) from the json through api call from controller. And if found then again fetching by filtering category.从 controller 的 api 调用中获取此 json,并希望从 json 到 881290284135988 从 controller 调用中获取嵌套值,例如(footwearlist,clothinglist)。如果找到,则通过过滤类别再次获取。

I tried using JsonPath with added dependency in pom.xml我尝试在 pom.xml 中使用添加了依赖项的 JsonPath

Dependency:依赖:

<dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.7.0</version>
        </dependency>

Tried to fetch the nested json but it didn,t work.试图获取嵌套的 json 但没有成功。

    public List<Store> getCategory(){
        List<Store> footwear = JsonPath.read(json, "$..footwear");
    }

There's no need to introduce a new dependency, there are several possible way to solve this problem using Jackson.不需要引入新的依赖,有几种可能的方法可以使用 Jackson 解决这个问题。

Jackson Streaming API Jackson 流媒体 API

If, for some reason, you don't want to materialize all data as objects and want to iterate over it.如果出于某种原因,您不想将所有数据具体化为对象并希望对其进行迭代。 Then generate a JsonNode from your JSON using ObjectMapper.readTree() , and examine the field-names of each nested node.然后使用ObjectMapper.readTree()从您的 JSON 生成一个JsonNode ,并检查每个嵌套节点的字段名称。 For that, you can use JsonNode.fields() .为此,您可以使用JsonNode.fields() If the matching field was encountered - grab the data.如果遇到匹配字段 - 获取数据。

To check whether a field is matching you can make use of the regular expression.要检查字段是否匹配,您可以使用正则表达式。 Here's regex-based predicate that would check if the given string contains substring "footwear" :这是基于正则表达式的谓词,它会检查给定的字符串是否包含 substring "footwear"

public static final Predicate<String> FOOTWEAR = Pattern.compile("footwear").asPredicate();

That's how the code for iterating over the tree having the structure you shown might look like:这就是迭代具有您显示的结构的树的代码可能如下所示:

String json = // incoming JSON
        
ObjectMapper mapper = new ObjectMapper();
        
List<Item> items = StreamSupport.stream(mapper.readTree(json).spliterator(), false)
    .<JsonNode>mapMulti((node, consumer) ->
        node.fields().forEachRemaining(entry -> {
            if (FOOTWEAR.test(entry.getKey())) entry.getValue().forEach(consumer);
        })
    )
    .map(StreamingNestedObjects::nodeToItem)
    .toList();
        
items.forEach(System.out::println);

Output: Output:

Item{id=1, name='sandals', category='men'}
Item{id=3, name='sandals', category='women'}
Item{id=2, name='shoes', category='men'}
Item{id=4, name='shoes', category='women'}

Assuming that Item class look like this:假设Item class 如下所示:

public class Item {
    private int id;
    private String name;
    private String category;
    
    // getters, setters, etc.
}

But the incoming JSON is not very massive, I would advise to make of the Jackson's Data binding.但是传入的 JSON 不是很大,我建议使用 Jackson 的数据绑定。

Data Binding数据绑定

Consider the following class Store :考虑以下 class Store

public class Store {
    private int id;
    private Map<String, List<Item>> items = new HashMap<>();
    
    @JsonAnySetter
    public void readStore(String key, List<Item> value) {
        items.put(key, value);
    }

    @JsonAnyGetter
    public Map<String, List<Item>> writeStore(String key, List<Item> value) {
        return items;
    }

    // no-args constructor, getter and setter for id property, etc.
}

One of its properties is a map of type Map<String, List<Item>> containing lists of items.它的一个属性是 map 类型的Map<String, List<Item>>包含项目列表。 This map can be serialized/deserialized via @JsonAnySetter and @JsonAnyGetter .这个 map 可以通过@JsonAnySetter@JsonAnyGetter序列化/反序列化。

That how you can parse your incoming JSON into a list of Store instances:那就是如何将传入的 JSON 解析为Store实例列表:

ObjectMapper mapper = new ObjectMapper();
        
List<Store> stores = mapper.readValue(json, new TypeReference<>() {});

Then iterate over the list, check the Keys of the Maps and pick the stores you need.然后遍历列表,检查地图的并选择您需要的商店。

暂无
暂无

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

相关问题 发布 API 使用 Spring 引导返回嵌套 Z466DEEC76ECDF5FCA6D38571F6324D5Z4 的 null 值 - Post API using Spring Boot returns null values for nested json 如何在 Spring Boot 中使用 RestTemplate 从来自外部 REST API 的 JSON 响应中提取数据? - How to extract data from JSON response coming from external REST API using RestTemplate in Spring Boot? 如何在Spring Boot中实现具有OneToMany关系的API返回嵌套的JSON? - How to implement API returns nested JSON with OneToMany relationship in Spring Boot? 如何在Spring Boot中测试对外部api的调用 - How to test a call to external api in Spring Boot Spring 引导 API 响应返回重复嵌套 JSON - Spring Boot API response returns repeating nested JSON 在Spring Boot中如何为请求生成JSON值? - How are JSON values generated for requests in Spring boot? 如何从另一个新的 Spring 启动项目中调用 Spring 启动项目中的 Spring 启动 api - How to call a Spring boot api present in one Spring boot project from another new Spring boot project 如何从Java中从GoogleDistanceMatrix API接收的JSON中提取嵌套值? - How to extract nested values from JSON received from GoogleDistanceMatrix API in Java? 如何在 Spring Boot 中使用 Java 从 JSON 响应中提取特定部分? - How to extract a specific part from JSON response with Java in Spring Boot? 如何在 Spring 引导应用程序中提取单个 JSON 属性? - How to extract a single JSON property in Spring Boot Application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM