如何从嵌套的JSON中获取一个键的所有值

huangapple go评论111阅读模式
英文:

how to get all values of a key from a nested json

问题

{
"pic": "1.jpg",
"products": [
{
"id": 1,
"pic": "4.jpg"
}
]
}

现在我想要提取所有数组或列表中的pic键。
结果必须是:["1.jpg","4.jpg"]

英文:

for example I have a json object like this:

{
"pic":"1.jpg",
"products":[
{
"id":1,
"pic":"4.jpg"
}
]

}

now I want to fetch all pic key inside an array or a list.
the result must be: ["1.jpg","4.jpg"]

答案1

得分: 4

在jackson库中,有一个简单的解决方案。

String value = "{\"pic\":\"1.jpg\",\"products\":[{\"id\":1,\"pic\":\"4.jpg\"}]}";
JsonNode jsonNode = new ObjectMapper().readTree(value);
System.out.println(jsonNode.findValuesAsText("pic"));

您可以通过以下Maven依赖添加jackson库。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.1</version>
</dependency>

您也可以传递文件或输入流给readTree()方法。

英文:

There is a simple solution for this in jackson library.

String value = &quot;{\&quot;pic\&quot;:\&quot;1.jpg\&quot;,\&quot;products\&quot;:[{\&quot;id\&quot;:1,\&quot;pic\&quot;:\&quot;4.jpg\&quot;}]}&quot;;
JsonNode jsonNode = new  ObjectMapper().readTree(value);
System.out.println(jsonNode.findValuesAsText(&quot;pic&quot;));

You can add jackson by using following maven dependency.

&lt;dependency&gt;
    &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
    &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
    &lt;version&gt;2.11.1&lt;/version&gt;
&lt;/dependency&gt;

You can also pass file, inputstream to readTree().

答案2

得分: 0

请尝试以下代码:

// 定义一个包含图片名称的列表
List<String> picList = new ArrayList<>();
try {
    // jsonMap: 你的 JSON 对象变量名
    String picName = (String) jsonMap.get("pic");
    picList.add(picName);

    List<Map<String, Object>> products = (List<Map<String, Object>>) jsonMap.get("products");
    for (Map<String, Object> product : products) {
        String pic = (String) product.get("pic");
        picList.add(pic);
    }

    System.out.println("=====图片列表====" + picList);
} catch (Exception e) {

}
英文:

Please try this code:

    //define a list which will contain pic names
    List&lt;String&gt; picList = new ArrayList&lt;&gt;();
    try {
        //jsonMap: your json object variable name
        String picName = (String) jsonMap.get(&quot;pic&quot;);
        picList.add(picName);
    
        List&lt;Map&lt;String, Object&gt;&gt; products = (List&lt;Map&lt;String, Object&gt;&gt;) jsonMap.get(&quot;products&quot;);
        for (Map&lt;String, Object&gt; product : products) {
            String pic = (String) product.get(&quot;pic&quot;);
            picList.add(pic);
        }
    
        System.out.println(&quot;=====List of pics====&quot;+picList);
    } catch (Exception e) {
    
    }

答案3

得分: 0

Sure, here's the translated code snippet:

// 最好将JSON解析为POJO类。您可以使用Gson将JSON字符串转换为以下Data类对象。

String jsonString = "您的JSON字符串在此";
Data object = new Gson().fromJson(jsonString, Data.class);

// 现在您有了该对象,可以从中获取产品列表,然后迭代获取“pic”值。

// 下面是Data类

package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Data {

    @SerializedName("pic")
    @Expose
    private String pic;
    @SerializedName("products")
    @Expose
    private List<Product> products = null;

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }
}
// 下面是Product类

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Product {

    @SerializedName("id")
    @Expose
    private int id;
    @SerializedName("pic")
    @Expose
    private String pic;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }
}
英文:

It would be better if you parse the json to a POJO class. You can use Gson to convert json string to below Data class object.

String jsonString = &quot;you json string here&quot;
Data object = Gson().fromJson(jsonString, Data.class)

Now you have the object and can get product list from which you can iterate and get "pic" values.

Below is the class

package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Data {

@SerializedName(&quot;pic&quot;)
@Expose
private String pic;
@SerializedName(&quot;products&quot;)
@Expose
private List&lt;Product&gt; products = null;

public String getPic() {
return pic;
}

public void setPic(String pic) {
this.pic = pic;
}

public List&lt;Product&gt; getProducts() {
return products;
}

public void setProducts(List&lt;Product&gt; products) {
this.products = products;
}

}
-----------------------------------com.example.Product.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Product {

@SerializedName(&quot;id&quot;)
@Expose
private int id;
@SerializedName(&quot;pic&quot;)
@Expose
private String pic;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getPic() {
return pic;
}

public void setPic(String pic) {
this.pic = pic;
}

}

答案4

得分: 0

如果您想获取产品节点内的图片列表,那么您可以将整个JSON数据转换为JSONObject,然后遍历内部的JSONArray

String str = "{\n" +
        "\"pic\":\"1.jpg\",\n" +
        "\"products\":[\n" +
        "{\n" +
        "\"id\":1,\n" +
        "\"pic\":\"4.jpg\"\n" +
        "}\n" +
        "]\n" +
        "}\n";

ArrayList<String> list = new ArrayList<>();

try {
    JSONObject root = new JSONObject(str);
    JSONArray products = root.getJSONArray("products");

    for (int i = 0; i < products.length(); i++) {
        String value = ((JSONObject) products.get(i)).getString("pic");
        list.add(value);
    }

} catch (JSONException e) {
    e.printStackTrace();
}

Log.d(TAG, "onCreate: " + list);
英文:

If you want the list of pics within the products node, then you can get the entire JSON into a JSONObject, and iterate over the inner JSONArray

String str = &quot;{\n&quot; +
        &quot;\&quot;pic\&quot;:\&quot;1.jpg\&quot;,\n&quot; +
        &quot;\&quot;products\&quot;:[\n&quot; +
        &quot;{\n&quot; +
        &quot;\&quot;id\&quot;:1,\n&quot; +
        &quot;\&quot;pic\&quot;:\&quot;4.jpg\&quot;\n&quot; +
        &quot;}\n&quot; +
        &quot;]\n&quot; +
        &quot;\n&quot; +
        &quot;}&quot;;

ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();

try {
    JSONObject root = new JSONObject(str);
    JSONArray products = root.getJSONArray(&quot;products&quot;);

    for (int i = 0; i &lt;= products.length(); i++) {
        String value = ((JSONObject) products.get(i)).getString(&quot;pic&quot;);
        list.add(value);
    }

} catch (JSONException e) {
    e.printStackTrace();
}

Log.d(TAG, &quot;onCreate: &quot; + list);

huangapple
  • 本文由 发表于 2020年8月3日 01:02:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63218787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定