-2

I am trying to figure out (using json-simple) how to get the name of an object within an object. For example:

{ { "objs": { "obj1": "blah", "obj2": "blah" } } }

I would like to get the value obj1 and obj2 (as they're the names of the objects, which is what I want). How would I do this with JSON-Simple and Java and put them into a String[]?

4

1 回答 1

1

您可以使用org.json库。

Maven依赖:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20150729</version>
</dependency>

jar下载: http: //mvnrepository.com/artifact/org.json/json

谷歌 gson

Maven依赖

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.4</version>
</dependency>

jar 下载: http: //mvnrepository.com/artifact/com.google.code.gson/gson/2.4

组织 json 示例

import org.json.JSONObject;

.

JSONObject jsonObject = new JSONObject("{ 'objs': { 'obj1': 'blah', 'obj2': 'blah' } } ");

JSONObject objs = jsonObject.getJSONObject("objs");

String obj1 = objs.getString("obj1");
String obj2 = objs.getString("obj1");

System.out.println(obj1);
System.out.println(obj2);

谷歌 gson 示例

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

.

JsonParser parser=new JsonParser();

JsonObject object=(JsonObject)parser.parse("{ 'objs': { 'obj1': 'blah', 'obj2': 'blah' } } ");

JsonObject objs2 = object.get("objs").getAsJsonObject();

String value1=objs2.get("obj1").getAsString();
String value2=objs2.get("obj2").getAsString();

System.out.println(value1);
System.out.println(value2);

JSON simple 是一个不再维护的旧库,上一个版本是 2012 年。 google gson最后org json一个版本是 2015 年,无论如何,如果你想使用旧库,请查看文档:

https://code.google.com/p/json-simple/wiki/DecodingExamples

于 2015-11-22T12:17:57.260 回答