简体   繁体   English

如何将此 JSON 转换为 Java 对象?

[英]How can i convert this JSON to Java Object?

I'm learning JACKSON.我正在学习杰克逊。 To train my skills i want to get field "URL" from following JSON:为了训练我的技能,我想从以下 JSON 中获取字段“URL”: 1

How can i do that?我怎样才能做到这一点? I don't need whole JSON-object, just one field (URL).我不需要整个 JSON 对象,只需要一个字段(URL)。

You don't need to convert the JSON into a Java Object for that you will need to define POJOS.您不需要将 JSON 转换为 Java 对象,因为您需要定义 POJOS。 Maybe this will help :-也许这会有所帮助:-

final ObjectNode yourNode = new ObjectMapper().readValue(<Your_JSON_Input_String>, ObjectNode.class);
if (node.has("URL")) {
    System.out.println("URL :- " + node.get("URL"));
}
import org.json.JSONArray;
import org.json.JSONObject;

public class Main {
    public static void main(String[] args) throws IOException {
        String jsonString = "{\"data\":[{\"url\":\"http://example.com\"}]}";

        JSONObject jsonObject = new JSONObject(jsonString); // 1

        JSONArray data = jsonObject.getJSONArray("data"); // 2

        JSONObject objectAtIndex0 = data.getJSONObject(0); // 3

        String urlAtObject0 = objectAtIndex0.getString("url"); // 4

        System.out.println(urlAtObject0);
    }
}
  1. Get JSON object for whole JSON string获取整个 JSON 字符串的 JSON 对象

  2. Get data as JSON array以 JSON 数组形式获取data

  3. Get JSON object at desired index or loop on JSON array of previous step在所需索引处获取 JSON 对象或在上一步的 JSON 数组上循环

  4. Get url field of the JSON object获取 JSON 对象的url字段

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM