在不知道键的情况下解析 json [重复]

问题描述 投票:0回答:3

我试图在java中解析json而不知道json格式的键和结构并将该数据保存到哈希图中

我如何循环遍历整个 json 格式并将键和值存储到哈希图中

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

就像在这个例子中一样,所有的键都是 jsonobject,没有一个是 json 数组

还有其他一些库,例如杰克逊,我不想使用任何第三方库

java android json
3个回答
3
投票

可能的解决方案:

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

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


0
投票

quick-json 解析器怎么样

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

-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]
© www.soinside.com 2019 - 2024. All rights reserved.