我有以下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"
    }
  ]
}

当前回答

可以使用Apache @Model注释创建表示JSON文件结构的Java模型类,并使用它们访问JSON树中的各种元素。与其他解决方案不同,该解决方案完全没有反射,因此适用于不可能反射或开销很大的环境。

有一个示例Maven项目展示了这种用法。首先它定义了结构:

@Model(className="RepositoryInfo", properties = {
    @Property(name = "id", type = int.class),
    @Property(name = "name", type = String.class),
    @Property(name = "owner", type = Owner.class),
    @Property(name = "private", type = boolean.class),
})
final class RepositoryCntrl {
    @Model(className = "Owner", properties = {
        @Property(name = "login", type = String.class)
    })
    static final class OwnerCntrl {
    }
}

然后它使用生成的RepositoryInfo和Owner类来解析所提供的输入流,并在此过程中获取某些信息:

List<RepositoryInfo> repositories = new ArrayList<>();
try (InputStream is = initializeStream(args)) {
    Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
}

System.err.println("there is " + repositories.size() + " repositories");
repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
    System.err.println("repository " + repo.getName() + 
        " is owned by " + repo.getOwner().getLogin()
    );
})

就是这样!除此之外,这里还有一个生动的要点,展示了类似的例子以及异步网络通信。

其他回答

本页的热门答案使用了太简单的例子,比如只有一个属性的对象(例如{name: value})。我认为这个简单但真实的例子可以帮助到一些人。

这是谷歌Translate API返回的JSON:

{
  "data": 
     {
        "translations": 
          [
            {
              "translatedText": "Arbeit"
             }
          ]
     }
}

我想检索“translatedText”属性的值。“Arbeit”使用谷歌的Gson。

两种可能的方法:

Retrieve just one needed attribute String json = callToTranslateApi("work", "de"); JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); return jsonObject.get("data").getAsJsonObject() .get("translations").getAsJsonArray() .get(0).getAsJsonObject() .get("translatedText").getAsString(); Create Java object from JSON class ApiResponse { Data data; class Data { Translation[] translations; class Translation { String translatedText; } } } ... Gson g = new Gson(); String json =callToTranslateApi("work", "de"); ApiResponse response = g.fromJson(json, ApiResponse.class); return response.data.translations[0].translatedText;

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");

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

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

The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.

javax.json.JsonReader jr = 
    javax.json.Json.createReader(new StringReader(jsonText));
javax.json.JsonObject jo = jr.readObject();

//Read the page info.
javax.json.JsonObject pageInfo = jo.getJsonObject("pageInfo");
System.out.println(pageInfo.getString("pageName"));

//Read the posts.
javax.json.JsonArray posts = jo.getJsonArray("posts");
//Read the first post.
javax.json.JsonObject post = posts.getJsonObject(0);
//Read the post_id field.
String postId = post.getString("post_id");

现在,在大家对这个答案投反对票之前因为它没有使用GSON, org。json, Jackson或任何其他可用的第三方框架,它是每个问题解析所提供文本的“所需代码”的示例。我很清楚JDK 9没有考虑遵守当前标准JSR 353,因此JSR 353规范应该与任何其他第三方JSON处理实现一样对待。

如果你的数据很简单,你不想要外部依赖,可以使用以下几行代码:

/**
 * A very simple JSON parser for one level, everything quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    for (int i = 1; i + 3 < qs.length; i += 4) {
        map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
    }
    return map;
}

这些数据

{"name":"John", "age":"30", "car":"a \"quoted\" back\\slash car"}

生成一个包含

{age=30, car=a "quoted" back\slash car, name=John}

这也可以升级为使用未加引号的值…

/**
 * A very simple JSON parser for one level, names are quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\",  "\\").split("\"");
    for (int i = 1; i + 1 < qs.length; i += 4) {
        if (qs[i + 1].trim().length() > 1) {
            String x = qs[i + 1].trim();
            map.put(qs[i].replace('\u0001', '"'), x.substring(1, x.length() - 1).trim().replace('\u0001', '"'));
            i -= 2;
        } else {
            map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
        }
    }
    return map;
}

为了解决复杂的结构,它变得很难看… ... 对不起! !... 但我忍不住把它编码了^^ 这将解析给定的JSON以及更多内容。它产生嵌套的映射和列表。

/**
 * A very simple JSON parser, names are quoted.
 * 
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, Object> simpleParseJson(String json) {
    Map<String, Object> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    int index[] = { 1 };
    recurse(index, map, qs);
    return map;
}

/**
 * Eierlegende Wollmilchsau.
 * 
 * @param index index into array.
 * @param map   the current map to fill.
 * @param qs    the data.
 */
private static void recurse(int[] index, Map<String, Object> map, String[] qs) {
    int i = index[0];
    for (;; i += 4) {
        String end = qs[i - 1].trim(); // check for termination of an object
        if (end.startsWith("}")) {
            qs[i - 1] = end.substring(1).trim();
            i -= 4;
            break;
        }

        String key = qs[i].replace('\u0001', '"');
        String x = qs[i + 1].trim();
        if (x.endsWith("{")) {
            x = x.substring(0, x.length() - 1).trim();
            if (x.endsWith("[")) {
                List<Object> list = new ArrayList<>();
                index[0] = i + 2;
                for (;;) {
                    Map<String, Object> inner = new TreeMap<>();
                    list.add(inner);
                    recurse(index, inner, qs);
                    map.put(key, list);
                    i = index[0];

                    String y = qs[i + 3]; // check for termination of array
                    if (y.startsWith("]")) {
                        qs[i + 3] = y.substring(1).trim();
                        break;
                    }
                }
                continue;
            }

            Map<String, Object> inner = new TreeMap<>();
            index[0] = i + 2;
            recurse(index, inner, qs);
            map.put(key, inner);
            i = index[0];
            continue;
        }
        if (x.length() > 1) { // unquoted
            String value = x.substring(1, x.length() - 1).trim().replace('\u0001', '"');
            if ("[]".equals(value)) // handle empty array
                map.put(key, new ArrayList<>());
            else
                map.put(key, value);
            i -= 2;
        } else {
            map.put(key, qs[i + 2].replace('\u0001', '"'));
        }
    }
    index[0] = i;
}

yield -如果你打印地图:

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