2014-09-05 74 views
4

我试图解析Java中的JSON不知道键和JSON格式的结构和数据保存到HashMap中的键解析JSON没有knowning

我将如何在整个JSON格式和存储关键周期和值到HashMap中

{"id" : 12345, "value" : "123", "person" : "1"} 

就像这个例子所有的按键将是他们的JSONObject没有将JSON数组

有没有像杰克逊的一些其他图书馆,我不希望使用任何第三方图书馆

+0

如果你的json格式良好,你可以使用Volley lib。如果你喜欢按照你的方式做事,也许你可以使用Gson。 – 2014-09-05 07:48:00

回答

4

这只是一个例子。 对于JSON像

{ 
"status": "OK", 
"search_result": [ 

      { 
       "product": "abc", 
       "id": "1132", 
       "question_mark": { 
        "141": { 
         "count": "141", 
         "more_description": "this is abc", 
         "seq": "2" 
        }, 
        "8911": { 
         "count": "8911", 
         "more_desc": "this is cup", 
         "seq": "1" 
        } 
       }, 
       "name": "some name", 
       "description": "This is some product" 
      }, 
      { 
       "product": "XYZ", 
       "id": "1129", 
       "question_mark": { 
        "379": { 
         "count": "379", 
         "more_desc": "this is xyz", 
         "seq": "5" 
        }, 
        "845": { 
         "count": "845", 
         "more_desc": "this is table", 
         "seq": "6" 
        }, 
        "12383": { 
         "count": "12383", 
         "more_desc": "Jumbo", 
         "seq": "4" 
        }, 
        "257258": { 
         "count": "257258", 
         "more_desc": "large", 
         "seq": "1" 
        } 
       }, 
       "name": "some other name", 
       "description": "this is some other product" 
      } 
     ] 
} 

使用JSONObject的键()拿到钥匙,然后遍历每个键进入动态值。

大致代码如下:

// searchResult refers to the current element in the array "search_result" 
JSONObject questionMark = searchResult.getJSONObject("question_mark"); 
Iterator keys = questionMark.keys(); 

while(keys.hasNext()) { 
    // loop to get the dynamic key 
    String currentDynamicKey = (String)keys.next(); 

    // get the value of the dynamic key 
    JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey); 

    // do something here with the value... 
} 

试试这个代码太

public void parse(String json) { 
    JsonFactory factory = new JsonFactory(); 

    ObjectMapper mapper = new ObjectMapper(factory); 
    JsonNode rootNode = mapper.readTree(json); 

    Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields(); 
    while (fieldsIterator.hasNext()) { 

     Map.Entry<String,JsonNode> field = fieldsIterator.next(); 
     System.out.println("Key:"field.getKey() + "\tValue:" + field.getValue()); 
    } 

}

也给看看这个链接

https://github.com/alibaba/fastjson

0

什么quick-json parser

JsonParserFactory factory=JsonParserFactory.getInstance(); 
JsonParser parser=factory.newJsonParser(); 
Map jsonData=parser.parseJson(inputJsonString); 
1

可能的解决办法:

private HashMap<String, Object> getHashMapFromJson(String json) throws JSONException { 
    HashMap<String, Object> map = new HashMap<String, Object>(); 
    JSONObject jsonObject = new JSONObject(json); 
    for (Iterator<String> it = jsonObject.keys(); it.hasNext();) { 
     String key = it.next(); 
     map.put(key, jsonObject.get(key)); 
    } 
    return map; 
} 

测试你的榜样JSON字符串:

private void test() { 
    String json = " {\"id\" : 12345, \"value\" : \"123\", \"person\" : \"1\"}"; 
    try { 
     HashMap<String, Object> map = getHashMapFromJson(json); 
     for (String key : map.keySet()) { 
      Log.i("JsonTest", key + ": " + map.get(key)); 
     } 
    } catch (JSONException e) { 
     Log.e("JsonTest", "Failed parsing " + json, e); 
    } 

} 

输出:

I/JsonTest(24833): id: 12345 
I/JsonTest(24833): value: 123 
I/JsonTest(24833): person: 1 

注:此并不理想,我只是写得很快。

-1
// add this in your android App module 

    compile 'com.fasterxml.jackson.core:jackson-core:2.5.3' 
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.5.3' 
    compile 'com.fasterxml.jackson.core:jackson-databind:2.5.3' 
android { 
    packagingOptions { 
     exclude 'META-INF/DEPENDENCIES.txt' 
     exclude 'META-INF/LICENSE.txt' 
     exclude 'META-INF/NOTICE.txt' 
     exclude 'META-INF/NOTICE' 
     exclude 'META-INF/LICENSE' 
     exclude 'META-INF/DEPENDENCIES' 
     exclude 'META-INF/notice.txt' 
     exclude 'META-INF/license.txt' 
     exclude 'META-INF/dependencies.txt' 
     exclude 'META-INF/LGPL2.1' 
     exclude 'META-INF/ASL2.0' 
    } 
} 
// now in main activity... 

// here is working code for parsing and differentiating keys and values without knowing the structure of the json 
ArrayList<String> jsonKeys; 
    Object[] arr3; 
    ArrayList<String> jKeys; 


    ArrayList<String> jsonValues; 
    Object[] arr2; 
    ArrayList<String> jValues; 

dataObject = new ArrayList<String>(); 
     jKeys = new ArrayList<String>(); 
     jValues = new ArrayList<String>(); 

     final String json = "{\"code\":100,\"payload\":{\"address1\":\"sggsgzg\",\"didPassWelcome\":false,\"didSetPasscode\":false,\"didSetPassword\":false,\"didVerifyDwolla\":false,\"didVerifyEmail\":false,\"email\":\"[email protected]\",\"firstName\":\"waseem\",\"id\":107,\"isStriprConnected\":true,\"lastName\":\"imran\",\"phone\":\"923017948684\",\"profileImage\":\"http://staging.api.giivv.com/resources/9cc82b7a-9665-4980-a54e-1ef45582cb66.jpg\",\"role\":4,\"userCreateTime\":\"2017-06-20\"}}"; 
       //String z = "{code:100,payload:{address1:sggsgzg,didPassWelcome:false,didSetPasscode:false,didSetPassword:false,didVerifyDwolla:false,didVerifyEmail:false,email:[email protected],firstName:waseem,id:107,isStriprConnected:true,lastName:imran,phone:923017948684,profileImage:http://staging.api.giivv.com/resources/9cc82b7a-9665-4980-a54e-1ef45582cb66.jpg,role:4,userCreateTime:2017-06-20}}"; 
// calling parsing method 
       parse2(json); 

//here is the method 

public void parse2(String json) { 
     try { 
      JsonFactory f = new JsonFactory(); 
      JsonParser token = f.createParser(json); 


      jsonKeys = new ArrayList<>(); 
      jsonValues = new ArrayList<>(); 

      String j = ""; 
      String key = ""; 

      while (token.nextToken() != JsonToken.END_OBJECT) { 

       if (token.getCurrentToken().equals(JsonToken.START_ARRAY)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
       //  Log.e("JSON value arrS:", j); 
        jsonValues.add(j); 

       } else if (token.getCurrentToken().equals(JsonToken.END_ARRAY)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
      //  Log.e("JSON value arrE:", j); 
        jsonValues.add(j); 


       } else if (token.getCurrentToken().equals(JsonToken.START_OBJECT)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
       //  Log.e("JSON value ObjectStart:", j); 
        jsonValues.add(j); 


       } else if (token.getCurrentToken().equals(JsonToken.END_OBJECT)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
      //   Log.e("JSON value ObjectEnd:", j); 
        jsonValues.add(j); 


       } else if (token.getCurrentToken().equals(JsonToken.FIELD_NAME)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
      //   Log.e("JSON value FieldName:", j); 
        jsonKeys.add(j); 


       } else if (token.getCurrentToken().equals(JsonToken.VALUE_FALSE)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
      //   Log.e("JSON value False:", j); 
        jsonValues.add(j); 

       } else if (token.getCurrentToken().equals(JsonToken.VALUE_NULL)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
      //   Log.e("JSON value null:", j); 
        jsonValues.add(j); 

       } else if (token.getCurrentToken().equals(JsonToken.VALUE_NUMBER_FLOAT)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
      //   Log.e("JSON value NumFLOAT:", j); 
        jsonValues.add(j); 

       } else if (token.getCurrentToken().equals(JsonToken.VALUE_NUMBER_INT)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
     //   Log.e("JSON value NumINT:", j); 
        jsonValues.add(j); 

       } else if (token.getCurrentToken().equals(JsonToken.VALUE_STRING)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
     //   Log.e("JSON value STRING:", j); 
        jsonValues.add(j); 


       } else if (token.getCurrentToken().equals(JsonToken.VALUE_TRUE)) { 
        System.out.println(token.getText()); 
        j = token.getText(); 
     //   Log.e("JSON value TRUE", j); 
        jsonValues.add(j); 

       } else { 
        System.out.println(token.getText()); 
        j = token.getText(); 
      //   Log.e("JSON value ELSE:", j); 
        jsonValues.add(j); 
       } 
      } 
      System.out.println("MY JSON KV FILE"); 
      System.out.println("this is the file \n"); 

      arr3 = new Object[jsonKeys.size()]; 
      arr3 = (Object[]) jsonKeys.toArray(); 

      for (Object t : arr3) { 

       Log.e("JSON KEy File:", (String) t); 
       jKeys.add(t.toString()); 

      } 

      arr2 = new Object[jsonValues.size()]; 
      arr2 = (Object[]) jsonValues.toArray(); 


      for (Object t2 : arr2) { 

       Log.e("JSON Value File:", (String) t2); 
       jValues.add(t2.toString()); 

      } 

     } catch (Exception e) { 
      System.out.println(e); 

     } 
    } 
// output in console: 
JsonKeys: 17 

JsonKeys: [code, payload, address1, didPassWelcome, didSetPasscode, didSetPassword, didVerifyDwolla, didVerifyEmail, email, firstName, id, isStriprConnected, lastName, phone, profileImage, role, userCreateTime] 

JsonValues: 18 

JsonValues: [{, 100, {, sggsgzg, false, false, false, false, false, [email protected], waseem, 107, true, imran, 923017948684, http://staging.api.giivv.com/resources/9cc82b7a-9665-4980-a54e-1ef45582cb66.jpg, 4, 2017-06-20] 
+1

如果你添加这样的代码墙,请考虑添加一些解释它的作用,以及它如何帮助 – 2017-10-02 08:29:20