【问题标题】:Parse Json with com.fasterxml.jackson instead of org.json使用 com.fasterxml.jackson 而不是 org.json 解析 Json
【发布时间】:2015-05-27 22:38:39
【问题描述】:

我想知道是否可以使用 jackson 库执行此精确操作。

String repo = response.toString();
JSONObject json = new JSONObject (repo);
String nameOfUser = json.getJSONObject(facebookID).getString("name");

谢谢,

【问题讨论】:

    标签: java json parsing jackson


    【解决方案1】:

    是的。比如:

    ObjectMapper mapper = new ObjectMapper(); // reuse, usually static final
    JsonNode ob = mapper.readTree(response.toString()); // or from File, URL, InputStream, Reader
    String nameOfUser = ob.path(facebookID).path("name").asText();
    // note: '.get()' also works, but returns nulls, 'path()' safer
    

    虽然更方便的访问通常使用 JSON 指针表达式完成,例如:

    String name = ob.at("/person/id").asText();    
    

    但我认为 facebookID 是来自其他来源的 id。

    更新:根据下面的评论,您想要的结构实际上可能是 POJO:

    public class Response {
      public User facebookID;
    }
    public class User {
       public String id;
       public String email;
       public String first_name;
       // ... and so forth: fields and/or getter+setter
    }
    

    然后你可以像这样直接绑定到类中:

    Response resp = mapper.readValue(response.toString(), Response.class);
    String name = resp.facebookID.name;
    

    因此,与杰克逊合作的方法不止一种。

    【讨论】:

    • 返回的响应字符串看起来像这样 {"facebookID":{"id":"facebookID","email":"xxxxxxxxxxxxxxxxxxx","first_name":"Marcus","gender":"male","last_name":"Bengtsson","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/xxxxxxxxxxx\/","locale":"sv_SE","middle_name":"Peter","name":"Marcus Rufus Bengtsson"}} 但是,是的,谢谢,这正是我想要的。最近刚接触杰克逊。不知道为什么,但是感觉json比较好理解……
    • 为什么不创建模型这个 json 消息的 java 值对象呢?这样你就可以简单地做 valuObject.getXXXX()。
    • @user3191617 org.json 是一个小得多的包,所以也许它更容易“知道这一切”,让它看起来更简单。由于功能集更大,Jackson 拥有更大的 API,并且可能需要一段时间才能学会足够的感觉。
    猜你喜欢
    • 2013-12-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多