简体   繁体   English

Gson / Retrofit解析变量JSON

[英]Gson/Retrofit parse variable JSON

I'm struggling in parsing a JSON Object with variable content to a Java Object. 我正在努力将具有可变内容的JSON对象解析为Java对象。

Normally, I'd try to map a JSON Object to a POJO, however in this case I don't know what to do. 通常,我会尝试将JSON对象映射到POJO,但是在这种情况下,我不知道该怎么做。

My JSON looks like this: 我的JSON看起来像这样:

"parts": [
           [
             "text",
             "http://www.example.com/"
           ],
           [
             "page",
             [
               "http://www.example.com/",
               "\n\t\n\t\t\n\t\t\tSome of the Page Content preview here...",
               "",
               "/path/to/picture.jpg"
             ]
           ],
           [
             "text",
             "Another String here "
           ]
         ]

Running this piece of code trough a typical Json to Java Object converter doesn't work because this cannot be mapped to a simple POJO. 通过典型的Json到Java Object转换器运行这段代码是行不通的,因为无法将其映射到简单的POJO。

I tried converting to List<List<String>>> myObject; 我试图转换为List<List<String>>> myObject; but as expected this gives me an exception: 但是正如预期的那样,这给了我一个例外:

W: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 9563 path $[3]./object.parts[1][1]

I think I'll have to create a custom DeSerializer for this, however I have no idea where to start. 我想我必须为此创建一个自定义DeSerializer,但是我不知道从哪里开始。

Any help pointing me in the good direction would be greatly appreciated. 向我指出正确方向的任何帮助将不胜感激。

EDIT: As pointed out in the comments, is the JSON data supplied not in valid key-value pair formation. 编辑:如注释中所指出,是提供的JSON数据不是有效的键值对形式。 I've contacted the API providers and they will sort this out. 我已经联系了API提供程序,他们将对此进行解决。

Until I come across a way of dealing with this problem on the frontend, I'll keep this question open. 直到我在前端遇到解决此问题的方法之前,我都将保持此问题为准。

So after looking at this problem again after af few days, I've finally found a solution that works for my case! 因此,几天后再次查看此问题后,我终于找到了适用于我的情况的解决方案!

In stead of trying to parse the element into a String as in my first attempts. 而不是像我第一次尝试那样尝试将元素解析为String I'm now storing the data to a simple java.lang.Object 我现在将数据存储到一个简单的java.lang.Object

My model now looks like this: 我的模型现在看起来像这样:

@SerializedName("parts")
@Expose
private List<List<Object>> parts = new ArrayList<List<Object>>();

This prevents the GSON parsing process from crashing the app when the invalid array is detected. 当检测到无效数组时,这可以防止GSON解析过程使应用程序崩溃。

When trying to access the data, I now check if the Object is of type String , if this is the case I continue, ignoring all Arrays. 现在,当尝试访问数据时,我将检查Object是否为String类型,如果是这种情况,我将继续忽略所有数组。

In my code this looks like this: (In my case, I only need the text attribute of the first element in the parts array) 在我的代码中,该代码如下所示:(就我而言,我只需要parts数组中第一个元素的text属性)

 List<List<Object>> partList = myParsedObject.getParts();
    if (partList.size() > 0) {
        if (partList.get(0).size() > 1) {
            if (partList.get(0).get(1) instanceof String) {
                return partList.get(0).get(1).toString();
            }
        }
    }

The second element in the second array element is also an array in the JSON that you posted. 第二个数组元素中的第二个元素也是您发布的JSON中的一个数组。

Since GSON is expecting a list of lists of Strings, it fails to parse the document beginning at this point. 由于GSON需要一个字符串列表的列表,因此它无法从此处开始解析文档。

"parts": [
       ...,
       [
         "page",
         [  <--- Problematic array begin
           "http://www.example.com/",
           "\n\t\n\t\t\n\t\t\tSome of the Page Content preview here...",
           "",
           "/path/to/picture.jpg"
         ]
       ],
       ...
     ]

Your JSON is not well formatted, I tried checking your posted JSON onto an Online JSON Formatter and it cannot parse your JSON. 您的JSON格式不正确,我尝试将您发布的JSON检查到在线JSON格式器上 ,但它无法解析您的JSON。 You need to encapsulate that JSON inside curly braces, like this : 您需要将该JSON封装在花括号内,如下所示:

{"parts": [
       [
         "text",
         "http://www.example.com/"
       ],
       [
         "page",
         [
           "http://www.example.com/",
           "\n\t\n\t\t\n\t\t\tSome of the Page Content preview here...",
           "",
           "/path/to/picture.jpg"
         ]
       ],
       [
         "text",
         "Another String here "
       ]
     ]
}

That JSON will be successfully parsed by the Online JSON Formatter, and you should be able to parse it just fine. 该JSON将由Online JSON Formatter成功解析,并且您应该能够对其进行解析。 The problem is you have to work on lots of JSON Array which does not have any key to identify them. 问题是您必须处理大量的JSON Array ,而JSON Array却没有任何key可以识别它们。 Mapping it would be troublesome because of the JSON Array after the "page" string. 映射它会很麻烦,因为"page"字符串后面是JSON Array

If my suggested JSON can be mapped into a List<List<String>> POJO, you'll have to get the second element and manually parse it again, since the second array still have an array inside it. 如果我建议的JSON可以映射到List<List<String>> POJO,则您必须获取第二个元素并再次手动对其进行解析,因为第二个数组中仍包含一个数组。

Hope this helps and good luck!!! 希望这会有所帮助,并祝你好运!!!

Regards, 问候,

Reid 里德

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM