gpt4 book ai didi

java - Gson将长度为1的json数组解析为JsonArray对象而不是JsonObject对象

转载 作者:行者123 更新时间:2023-12-01 11:34:46 26 4
gpt4 key购买 nike

使用 Gson,我试图强制我的 json 对象具有一个包含一个元素的数组值。虽然我以这种方式构造 json,但 JsonParser 会创建一个新的 JsonObject 来代替长度为 1 的数组。我的系统中的大多数 json 都具有大于长度 1 的数组值,并且可以正确解析。

我在尝试使用实用方法将 JsonObject 强制转换为 JsonArray 时发现了这一点。它没有按照我的预期进行。

static JsonArray bruteForceJsonArray(JsonObject object, String key) {
if(object.get(key).isJsonArray()) {
return object.get(key).getAsJsonArray();
} else {
System.out.println("broken: " + object.toString());
JsonObject temp = object.get(key).getAsJsonObject();
String fixed = "{'" + key + "':[" + temp.toString() + "]}";
System.out.println("pre-fix: " + fixed);

//parsing here reduces the array to an object - hot to prevent?
temp = new JsonParser().parse(fixed).getAsJsonObject();
System.out.println("fixed: " + object.toString());
return object.get(key).getAsJsonArray();
}
}

输出:

broken: {"token":{"NER":"O","id":1.0,"word":".","CharacterOffsetEnd":765.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":764.0}}
pre-fix: {'token':[{"NER":"O","id":1.0,"word":".","CharacterOffsetEnd":765.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":764.0}]}
fixed: {"token":{"NER":"O","id":1.0,"word":".","CharacterOffsetEnd":765.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":764.0}}

大多数 json 在系统中正确显示的示例:

{"token":[{"Speaker":"PER0","POS":"IN","lemma":"except","CharacterOffsetBegin":742.0,"NER":"O","id":1.0,"word":"Except","CharacterOffsetEnd":748.0},{"CharacterOffsetEnd":752.0,"Speaker":"PER0","POS":"IN","lemma":"for","CharacterOffsetBegin":749.0,"NER":"O","id":2.0,"word":"for"},{"id":3.0,"word":"extra","CharacterOffsetEnd":758.0,"Speaker":"PER0","POS":"JJ","lemma":"extra","CharacterOffsetBegin":753.0,"NER":"O"},{"Speaker":"PER0","POS":"NN","lemma":"meat","CharacterOffsetBegin":759.0,"NER":"O","id":4.0,"word":"meat","CharacterOffsetEnd":763.0},{"CharacterOffsetEnd":764.0,"Speaker":"PER0","POS":".","lemma":".","CharacterOffsetBegin":763.0,"NER":"O","id":5.0,"word":"."}]}

有没有一个聪明的方法来解决这个问题 - 我可以通过某种方式有效地将我的对象强制放入数组中,这样我就可以在流中处理它们,而无需太多的 try/catch 或 if/else 处理?

最佳答案

static JsonArray bruteForceJsonArray(JsonObject object, String key) {
if (object.get(key).isJsonArray()) {
return object.get(key).getAsJsonArray();
} else {
JsonArray oneElementArray = new JsonArray();
oneElementArray.add(new JsonObject());
return oneElementArray;
}
}

尽管如此,您不应该直接使用 JsonObject/JsonArray。为您的数据创建一个 POJO 类并使用 Gson 反序列化 JSON。

关于java - Gson将长度为1的json数组解析为JsonArray对象而不是JsonObject对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30115363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com