Home > Software engineering >  How can i convert this JSON to Java Object?
How can i convert this JSON to Java Object?

Time:06-18

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).

CodePudding user response:

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"));
}

CodePudding user response:

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

  • Related