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

时间:2015-05-08 03:39:20

标签: java arrays json gson

使用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处理?

0 个答案:

没有答案