我有以下JSON文本。我如何解析它以获得pageName, pagePic, post_id等的值?

{
  "pageInfo": {
    "pageName": "abc",
    "pagePic": "http://example.com/content.jpg"
  },
  "posts": [
    {
      "post_id": "123456789012_123456789012",
      "actor_id": "1234567890",
      "picOfPersonWhoPosted": "http://example.com/photo.jpg",
      "nameOfPersonWhoPosted": "Jane Doe",
      "message": "Sounds cool. Can't wait to see it!",
      "likesCount": "2",
      "comments": [],
      "timeOfPost": "1234567890"
    }
  ]
}

当前回答

If one wants to create Java object from JSON and vice versa, use GSON or JACKSON third party jars etc. //from object to JSON Gson gson = new Gson(); gson.toJson(yourObject); // from JSON to object yourObject o = gson.fromJson(JSONString,yourObject.class); But if one just want to parse a JSON string and get some values, (OR create a JSON string from scratch to send over wire) just use JaveEE jar which contains JsonReader, JsonArray, JsonObject etc. You may want to download the implementation of that spec like javax.json. With these two jars I am able to parse the json and use the values. These APIs actually follow the DOM/SAX parsing model of XML. Response response = request.get(); // REST call JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class))); JsonArray jsonArray = jsonReader.readArray(); ListIterator l = jsonArray.listIterator(); while ( l.hasNext() ) { JsonObject j = (JsonObject)l.next(); JsonObject ciAttr = j.getJsonObject("ciAttributes");

其他回答

Quick-json解析器非常简单,灵活,快速,可定制。试一试

特点:

Compliant with JSON specification (RFC4627) High-Performance JSON parser Supports Flexible/Configurable parsing approach Configurable validation of key/value pairs of any JSON Hierarchy Easy to use # Very small footprint Raises developer friendly and easy to trace exceptions Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered Validating and Non-Validating parser support Support for two types of configuration (JSON/XML) for using quick-JSON validating parser Requires JDK 1.5 No dependency on external libraries Support for JSON Generation through object serialisation Support for collection type selection during parsing process

它可以这样使用:

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);

Jsoniter (jsoniterator)是一个相对较新的和简单的json库,旨在简单和快速。反序列化json数据所需要做的就是

JsonIterator.deserialize(jsonData, int[].class);

其中jsonData是json数据的字符串。

去官方网站看看吧 获取更多信息。

你可以用谷歌Gson。

使用这个库,您只需要创建一个具有相同JSON结构的模型。然后自动填充模型。你必须调用你的变量作为你的JSON键,或者使用@SerializedName如果你想使用不同的名字。

JSON

从你的例子中:

{
    "pageInfo": {
        "pageName": "abc",
        "pagePic": "http://example.com/content.jpg"
    }
    "posts": [
        {
            "post_id": "123456789012_123456789012",
            "actor_id": "1234567890",
            "picOfPersonWhoPosted": "http://example.com/photo.jpg",
            "nameOfPersonWhoPosted": "Jane Doe",
            "message": "Sounds cool. Can't wait to see it!",
            "likesCount": "2",
            "comments": [],
            "timeOfPost": "1234567890"
        }
    ]
}

模型

class MyModel {

    private PageInfo pageInfo;
    private ArrayList<Post> posts = new ArrayList<>();
}

class PageInfo {

    private String pageName;
    private String pagePic;
}

class Post {

    private String post_id;

    @SerializedName("actor_id") // <- example SerializedName
    private String actorId;

    private String picOfPersonWhoPosted;
    private String nameOfPersonWhoPosted;
    private String message;
    private String likesCount;
    private ArrayList<String> comments;
    private String timeOfPost;
}

解析

现在你可以使用Gson库进行解析:

MyModel model = gson.fromJson(jsonString, MyModel.class);

Gradle进口

记得在应用的Gradle文件中导入这个库

implementation 'com.google.code.gson:gson:2.8.6' // or earlier versions

自动生成模型

您可以使用这样的在线工具从JSON自动生成模型。

任何类型的json数组 解决问题的步骤。

将JSON对象转换为java对象。 你可以使用这个链接或任何在线工具。 保存为java类,如Myclass.java。 Myclass obj = new Gson().fromJson(JsonStr, Myclass.class); 使用obj,你可以得到你的值。

为了便于示例,让我们假设您有一个只有名称的Person类。

private class Person {
    public String name;

    public Person(String name) {
        this.name = name;
    }
}

谷歌GSON (Maven)

我个人最喜欢的JSON对象序列化/反序列化。

Gson g = new Gson();

Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John

System.out.println(g.toJson(person)); // {"name":"John"}

更新

如果你想获取单个属性,你可以很容易地使用谷歌库:

JsonObject jsonObject = new JsonParser().parse("{\"name\": \"John\"}").getAsJsonObject();

System.out.println(jsonObject.get("name").getAsString()); //John

Org。JSON (Maven)

如果您不需要对象反序列化,而只是获得一个属性,您可以尝试org。json(或查看上面的GSON示例!)

JSONObject obj = new JSONObject("{\"name\": \"John\"}");

System.out.println(obj.getString("name")); //John

杰克逊(Maven)

ObjectMapper mapper = new ObjectMapper();
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);

System.out.println(user.name); //John