从JSON字段中检索值

时间:2018-07-24 11:08:04

标签: java json

我试图检索参数“ position”及其X和Y。

int npcId = reader.get("npcId").getAsInt();
int x = reader.get("position").getAsInt();
int y = reader.get("position").getAsInt();
int z = 0;

此输入为JSON

{
    "npcId": 414,
    "position": {
        "x": 3443,
        "y": 3536,
        "z": 0
    },
    "facing": "WEST",
    "radius": 13
}

例如int x = reader.get("position.X").getAsInt();(显然不起作用,但您明白了。)

1 个答案:

答案 0 :(得分:0)

从您的帖子中可以看到,您想解析JSON输入并检索某些字段的值。

这里是一个示例,如果您想创建一个与JSON结构相对应的Java类。然后,您可以从JSON构建对象并直接检索该字段。 https://www.journaldev.com/2321/gson-example-tutorial-parse-json

我做过的另一种方法是从您的JSON构建一个映射,并对其进行迭代。在这种情况下,您应该知道您的JSON结构。这是一个例子 https://stackoverflow.com/a/12296567/4587961

1)将输入字符串解析为JSON对象。

2)遍历JSON对象并找到您需要的字段。

3)检索它们的值。

compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'

Gson gson = new Gson(); 
String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";//You input String
Map<String,Object> map = new HashMap<String,Object>();
//Check if map is not null and instance of Map.
map = (Map<String,Object>) gson.fromJson(json, map.getClass());
Object position = map.get("position");
//Check if position is not null and instance of Map. You can create a method to do this logic.
Map<String, Object> positionMap = (Map) position;
Object X = positionMap.get("x");
//Please, continue yourself.

您还可以使用其他库,例如Jackson。这是您的功课,请尝试学习有关JSON的更多信息,并尝试使用其他库,以及带有示例的github帐户的链接,以便其他人也可以学习。