How to get a value from a JSON string using jackson library?

后端 未结 3 887
余生分开走
余生分开走 2021-01-02 00:59

I am trying to get a value from a JSON string but I am getting a null value instead.

App2.java :

package JsonExample1;

import org.codehaus.jackson.J         


        
相关标签:
3条回答
  • 2021-01-02 01:03

    Convert to the Map

    Map map = objectMapper.readValue(jsonString, Map.class);
    

    Method for navigation in the map

    private static <T> T get(Map map, Class<T> clazz, String... path) {
        Map node = map;
        for (int i = 0; i < path.length - 1; i++) {
          node = (Map) node.get(path[i]);
        }
        return (T) node.get(path[path.length - 1]);
      }
    

    Usage:

    String value = get(map, String.class, "path", "to", "the", "node")
    
    0 讨论(0)
  • 2021-01-02 01:09

    Your root node doesn't have a customerSessionId, it has a HotelListResponse. Get that first.

    //other methods
    public void basicTreeModelRead()
    {
        JsonNode innerNode = rootNode.get("HotelListResponse"); // Get the only element in the root node
        // get an element in that node
        JsonNode aField = innerNode.get("customerSessionId");
    
        //the customerSessionId has a String value
        String myString = aField.asText();
    
        System.out.println("customerSessionId is:" + myString);
    }
    

    This prints

    customerSessionId is:0ABAAA7A-90C9-7491-3FF2-7E2C37496CA2
    
    0 讨论(0)
  • 2021-01-02 01:24

    Another way to get the inner element, with .at() method:

    rootNode.at("/HotelListResponse/customerSessionId")
    
    0 讨论(0)
提交回复
热议问题