gpt4 book ai didi

java - 用 Java 解析这个 JSON?

转载 作者:行者123 更新时间:2023-12-02 00:36:31 24 4
gpt4 key购买 nike

当解析 JSON 时,我通常只构造一个对象并使用 gson 库将我的字符串解析为该对象。

但是,我现在发现自己有一个相当复杂的响应,它由许多元素组成,每个元素都有对象的子元素、数组和对象数组。看起来像这样...

{
"type": "thetype",
"object":{
"text": "texthere",
"moretext": "more here"
},
...,
...,
...,
...,
"fieldIwant": [
{
"object":"object!"
},
....
....
{
"object":"object!"
},
]
}

问题是,我只对 fieldIwant 真正感兴趣,没有其他兴趣。在 Java 中是否没有一种方法可以让我提取该字段并单独使用它,而不需要所有其他我不需要的负担?

最佳答案

根据这个http://sites.google.com/site/gson/gson-design-document看起来 gson 默认情况下会为您执行此操作。

When you are deserializing a Json string into an object of desired type, you can either navigate the tree of the input, or the type tree of the desired type. Gson uses the latter approach of navigating the type of the target object. This keeps you in tight control of instantiating only the type of objects that you are expecting (essentially validating the input against the expected "schema"). By doing this, you also ignore any extra fields that the Json input has but were not expected.

换句话说,它不会反序列化您不需要的任何字段。你应该可以走了。

关于java - 用 Java 解析这个 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7667805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com