2015-06-25 35 views
2

我想嵌套的JSON陣列知道如何使用傑克遜庫中的Java構建URI一樣來解析以下JSON http://api.statdns.com/google.com/cname解析使用傑克遜庫在Java中

{ 
    "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 
     } 
    ] 
} 

我寫不好的代碼解析上面的json數組。以下是我使用的代碼,

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

任何人都可以幫助我知道使用傑克遜解析JSON嗎?非常感謝幫助。

+0

我在使用傑克遜之前已經回答了類似的問題:http://stackoverflow.com/a/30292422/3080094 – vanOekel

回答

0

我不知道JACKSON庫,但我認爲它與GSON類似。您只需製作一些POJO,圖書館將負責爲您填充字段。

例如向MyJSONClass使用以下類的字符串轉換:

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

這組類可以被轉換成JSON與傑克遜庫(thanks to this stackoverflow answer)這樣的:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); 
String json = ow.writeValueAsString(object); 
+0

@Trapll我只想使用傑克遜庫 – DIVA

+0

@DIVA明白你的意思,更新了我的答案。 – TrapII

+0

@Trapll爲什麼我應該使用POJO來解析JSON。有沒有可能解析這個json數組而不使用POJO類? – DIVA

1

如果你正在使用傑克遜庫,那麼你應該去這樣的事情:

我使用的響應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); 
     } 
} 

我在這裏做了「問題」而已,同樣也可以做其他如說「答案」在你所提到的情況下http://api.statdns.com/google.com/cname URL,「權威」。

希望它可以幫助你解決你的問題.. !!!!

+0

感謝您的回覆 – DIVA

0

如果你對JSON沒有變化有信心,簡化代碼的一種快速和骯髒的方法是使用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); 
} 

如果返回多個apicalls條目,這變得脆弱。

+0

我可以有多個APIcalls數組。我怎麼能解析每個數組來啓動此方法內的REST調用。 – DIVA