Parse JSON with unknown key?

后端 未结 2 915
慢半拍i
慢半拍i 2021-01-20 16:52

i have a Json output like this :

The numbers 2922 and 3910 are random numbers. How can i store all values that are in \"name\" in an array?

Thank yo

相关标签:
2条回答
  • 2021-01-20 17:00

    You can use Iterator.

    Using Iterator, you can iterate all elements of a list in either direction. You can access next element by calling next() method .

    JSONObject reader = new JSONObject(success);
                    Iterator  iteratorObj = reader .keys();
                    ArrayList<String> al_getAllKeys=new ArrayList<String>();
                    while (iteratorObj.hasNext())
                    {
                        String getJsonObj = (String)iteratorObj.next();
                        System.out.println("KEY: " + "------>" + getJsonObj);
    
                    }
    
    0 讨论(0)
  • 2021-01-20 17:06

    You can use the jackson tool to conver json to pojo Below is the snippet of code

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

    HapPy C@ding..!!

    0 讨论(0)
提交回复
热议问题