2

I would like to know how to parse the following JSON using jackson library in java to construct the URI like http://api.statdns.com/google.com/cname

{
    "status": {
        "status": 200,
        "msg": "SUCCESS"
     },
    "apicalls": [
        {
            "API": {
                "method": "get",
                "success": "200",
                "baseURL": "http://api.statdns.com/",
                "param1": "google.com/",
                "param2": "cname",
                "continue_on_fail": "1",
                "add_header2": "'Accept', 'application/json'",
                "add_header1": "'Content-Type', 'application/json'",
                "client_id": "101"
            },
            "id": 1385
        }
    ]
 }

I have written bad code to parse the above json array. Following is the code i used,

public void parseJSON(String json) {
    try{
    JsonFactory factory = new JsonFactory();
    JsonParser parser;
    parser = factory.createJsonParser(json);
    parser.setCodec(new ObjectMapper()); // to avoid IllegalStateException  
    JsonToken current;
    current = parser.nextToken();
    if (current != JsonToken.START_OBJECT) {
       System.out.println("Error: root should be object: quiting.");
                return;
            }

            while (parser.nextToken() != JsonToken.END_OBJECT) {
                String fieldName = parser.getCurrentName();
                // Move from field name to field value
                current = parser.nextToken();
                if (fieldName.equals("APIcalls")) {
                    JsonNode node = parser.readValueAsTree();
                    JsonNode currentJson = node.findValue("API");
                    System.out.println("Current JSON :: " + currentJson);

                    JsonNode url = currentJson.get("baseURL");
                    JsonNode param1 = currentJson.get("param1");
                    JsonNode param2 = currentJson.get("param2");

                    String baseURL = url.asText();
                    String params1 = param1.asText();
                    String params2 = param2.asText();
                    String uri = baseURL + params1 + params2;
                    System.out.println("URL :: " + uri);

                    initiateRESTCall(uri);

                }
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Could anyone help me to know parsing the JSON using jackson? Help is highly appreciated.

BoJack Horseman
  • 4,406
  • 13
  • 38
  • 70
DIVA
  • 549
  • 2
  • 11
  • 34

3 Answers3

1

If you are using jackson library, then you should go something like this:

I am using response from http://api.statdns.com/google.com/cname

public void parseJSON(String json) {
JSONObject parse = new JSONObject(data);

        if(parse.get("question") instanceof JSONObject){
            JSONObject questionJson = (JSONObject) parse.get("question"); 
            System.out.println("Name"+questionJson.getString("name"));
            System.out.println("Type"+questionJson.getString("type"));
            System.out.println("Class"+questionJson.getString("class"));

        }
        else if(parse.get("question") instanceof JSONArray){
            JSONArray questionJson = (JSONArray) parse.get("question"); 
            String[] nameAttrib=new String[questionJson.length()];
            String[] typeAttrib=new String[questionJson.length()];
            String[] classAttrib=new String[questionJson.length()];
            for(int i=0;i<questionJson.length();i++){
                JSONObject questionJsonData=(JSONObject)questionJson.get(i);
                nameAttrib[i]=questionJsonData.getString("name");
                typeAttrib[i]=questionJsonData.getString("type");
                classAttrib[i]=questionJsonData.getString("class");
                System.out.println("Name: "+nameAttrib[i]);
                System.out.println("Type: "+typeAttrib[i]);
                System.out.println("Class: "+classAttrib[i]);
            }

        }
        else if (parse.get("question").equals(null)){

            System.out.println("question"+null);
        }
}

Here I am doing for "question" only, similarly you can do other as well say "answer", "authority" in case url you have mentioned http://api.statdns.com/google.com/cname.

Hopefully it helps you with your problem..!!!!

ajitksharma
  • 4,523
  • 2
  • 21
  • 40
0

I don't know JACKSON library but I think it is similar to GSON. You just have to make some POJO and the library will take care of filling the fields for you.

For instance to convert your string to MyJSONClass use the following classes :

class Status {
    int status;
    String msg;
}
class APIClass {
    String method;
    String success;
    String baseURL;
    String param1;
    String param2;
    String continue_on_fail;
    String add_header2;
    String add_header1;
    String client_id;
}
class APICall {
    APIClass API;
    int id;
}
class MyJSONClass {
    Status status;
    List<APICall> apicalls;
}

This set of classes could be transformed to JSON with JACKSON library (thanks to this stackoverflow answer) like that:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
Community
  • 1
  • 1
TrapII
  • 2,219
  • 1
  • 15
  • 15
  • @Trapll I would like to use only jackson library – DIVA Jun 26 '15 at 06:09
  • @Trapll Why should i use the POJO's to parse the JSON. Is it possible to parse this json array without using POJO classes ? – DIVA Jun 26 '15 at 07:35
0

If you are confident in the JSON not changing, a quick and dirty way to simplify your code is to use JSON Pointers.

// prefer injecting your project's ObjectMapper
private static final ObjectMapper om = new ObjectMapper();

public void parseJSON(String json) throws IOException {
    JsonNode jsonNode = om.readTree(json);
    String uri = new StringBuilder(jsonNode.findValue("baseURL").asText())
            .append(jsonNode.findValue("param1").asText())
            .append(jsonNode.findValue("param2").asText())
            .toString();
    initiateRESTCall(uri);
}

This becomes vulnerable if multiple apicalls entries are returned.

Community
  • 1
  • 1
Sam Berry
  • 7,394
  • 6
  • 40
  • 58
  • I can have more than one array inside APIcalls. How could i parse each array to initiate the REST call inside this method. – DIVA Jun 26 '15 at 06:14