如何通过键获取嵌套的JSON内容?

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

How to get nested JSON content by key?

问题

以下是要翻译的代码部分:

static void getPost() throws Exception {
    String webPage = "https://www.reddit.com/r/arabfunny/top.json?limit=100";

    URL url = new URL(webPage);
    URLConnection request = url.openConnection();
    request.setRequestProperty("Content-Type", "application/json; utf-8");
    request.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

    JsonParser jp = new JsonParser();
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
    JsonObject rootobj = root.getAsJsonObject();
    String imageURL = rootobj.get("data").toString();
    System.out.println(imageURL);
}

要获取第一层数据之后的内容,您遇到了困难,您可以使用.get("data")来获取第一层数据,但无法使用.get("data").get("children")来获取第二层数据。

您可以尝试使用以下方式来获取随机子项(children),其中您不知道子项数量:

rootobj.get("data").getAsJsonObject().getAsJsonArray("children").get(RANDOM_INDEX).toString();

请注意,您需要将RANDOM_INDEX替换为实际的随机索引值。

如果您只需要从随机子项获取一些参数,您可以按照以下方式进行操作:

JsonObject data = rootobj.get("data").getAsJsonObject();
JsonArray children = data.getAsJsonArray("children");
int randomIndex = /* 生成随机索引的代码 */;
JsonObject randomChild = children.get(randomIndex).getAsJsonObject();
String subreddit = randomChild.get("data").getAsJsonObject().get("subreddit").getAsString();

请将上述代码中的/* 生成随机索引的代码 */替换为生成随机索引的实际代码。这将帮助您获取到从随机子项中获取的 subreddit(或其他最终字段)的值。

英文:

I have the following code which I use to download a JSON file from a URL:

static void getPost() throws Exception {
        String webPage = "https://www.reddit.com/r/arabfunny/top.json?limit=100";

        URL url = new URL(webPage);
        URLConnection request = url.openConnection();
        request.setRequestProperty("Content-Type", "application/json; utf-8");
        request.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

        JsonParser jp = new JsonParser();
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
        JsonObject rootobj = root.getAsJsonObject();
        String imageURL = rootobj.get("data").toString();
        System.out.println(imageURL);
    }

This correctly gets the code but I'm having trouble getting data past the first level, I can use .get("data") and that works as expected but I cannot do .get("data").get("children").

The JSON file can be found here.

Here is the JSON prettyfied.

如何通过键获取嵌套的JSON内容?

I want to get a random children where I don't know the number of children. Something like rootobj.get("data").get("children").get(RANDOM).toString();

EDIT:

I really just need a simple solution to get a few parameters from a random children.

如何通过键获取嵌套的JSON内容?

I need to get JSON -> data -> children[random item] -> data -> subreddrit (or other final field)

Can anyone show me a basic working example that would give me any final value which I can then modify?

答案1

得分: 1

使用Maven引入Jackson库

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.2</version>
</dependency>
ObjectMapper objectMapper = new ObjectMapper();
JsonNode node = objectMapper.readValue(<OUTPUT_JSON>, JsonNode.class);
rootobj.get("data").get("children")[INDEX].get(RANDOM).asText();
英文:

Use Jackson from maven

&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.2&lt;/version&gt;
&lt;/dependency&gt;
ObjectMapper objectMapper = new ObjectMapper();
JsonNode node = objectMapper.readValue(&lt;OUTPUT_JSON&gt;,JsonNode.class);
rootobj.get(&quot;data&quot;).get(&quot;children&quot;)[INDEX].get(RANDOM).asText();

答案2

得分: 1

对我来说,使用 Pojo 定义返回对象并使用 Gson 进行反序列化更容易。

Maven 依赖

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.3</version>
</dependency>

然后定义你的 Result Pojo

public class MyResult {

   public Data data;

   //getter

}

Data POJO

public class Data {

      public String modhash;
      public Integer dist;
      public List<Children> children; // 定义你的对象
      public String after;
      public String before;

      //getters
      
   }

Children POJO

public class Children {
     private String kind;
     private String data; // 如果需要的话,你可以定义另一个 Data 对象

     //getters
     
     //toString() 方法。
}

注意: 确保 JSON 字段名与 POJO 字段名完全相同。

将 Json 字符串转换为对象:

// 从请求获取 Json 字符串:开始
InputStream inputStream = request.getInputStream();
       
InputStreamReader isReader = new InputStreamReader(inputStream);
// 创建 BufferedReader 对象
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while((str = reader.readLine()) != null) {
   sb.append(str);
}
       
String jsonString = sb.toString();
// 从请求获取 Json 字符串:结束

MyResult result = new Gson().fromJson(jsonString, MyResult.class);
result.getData().getChildren()
    .get(0) // 从列表中获取索引 0
    .toString();

如果你不想创建太多层次的 Pojo,可以创建自己的 JsonAdapter。

我没有测试过这段代码,所以可能存在一些语法错误。

此外,你还可以查看 JsonPath 库,使用点符号表示法解析 JSON 文件。

英文:

For me it is easier to define your return object using Pojo and use Gson to deserialize it.

Maven dependency

&lt;!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;com.google.code.gson&lt;/groupId&gt;
    &lt;artifactId&gt;gson&lt;/artifactId&gt;
    &lt;version&gt;2.8.3&lt;/version&gt;
&lt;/dependency&gt;

Then define your Result Pojo

public class MyResult{

   public Data data;

   //getter

}

//Data POJO

public class Data{

      public String modhash;
      public Integer dist;
      public List&lt;Children&gt; children; //define your object
      public String after;
      public String before;

      //getters
      
   }

Children POJO

public class Children{
     private String kind;
     private String data; //You can define another Data Object if you want to

     //getters
     
     //toString() method.
}

NOTE: Make sure that JSON field names are exactly the same as POJO field names.

To convert Json string to object:

//get Json String from request : START
InputStream inputStream = request.getInputStream();
       
InputStreamReader isReader = new InputStreamReader(inputStream);
//Creating a BufferedReader object
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while((str = reader.readLine())!= null){
   sb.append(str);
}
       
String jsonString = sb.toString();
//get Json String from request : END
		
MyResult result = new Gson().fromJson(jsonString,MyResult.class)
result.getData().getChildren()
    .get(0) //get index 0 from list
    .toString();

If you do not want to create too many layer of Pojos, create your own JsonAdapter.

I haven't tested this so there might be some syntax error.

Also you can look at JsonPath library for parsing json file using dot notation.

huangapple
  • 本文由 发表于 2020年8月9日 11:55:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63322308.html
匿名

发表评论

匿名网友

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

确定