简体   繁体   中英

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: 1

How can i do that? I don't need whole JSON-object, just one field (URL).

You don't need to convert the JSON into a Java Object for that you will need to define 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

  2. Get data as JSON array

  3. Get JSON object at desired index or loop on JSON array of previous step

  4. Get url field of the JSON object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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