简体   繁体   中英

Unable to parse JSON file using GSON library

I am unable to parse this JSON file. Any suggestions are appreciated. I have created POJO classes from http://www.jsonschema2pojo.org/ I tried JSON deserilization solution mentioned but it did not work out for me.

    {
  "error": "",
  "data": [
    {
      "view": "Viewpapger",
      "data": [
        {
          "view": "ImageView",
          "data": {
            "url": "random.jpg"
          },
          "properties": {
            "width": "fill_parent",
            "height": "500"
          }
        },
        {
          "view": "Textview",
          "data": {
            "text": "afvnjkafvf"
          },
          "properties": {
            "width": "fill_parent"
          }
        },
        {
          "view": "Textview",
          "data": {
            "text": "afvnjkafvf"
          },
          "properties": {
            "width": "fill_parent"
          }
        },
        {
          "view": "ImageView",
          "data": {
            "url": "random.jpg"
          },
          "properties": {
            "width": "fill_parent",
            "height": "500"
          }
        }
      ],
      "properties": {
        "width": "wrap_content",
        "height": "500"
      }
    },
    {
      "view": "Textview",
      "data": {
        "text": "afvnjkafvf"
      },
      "properties": {
        "width": "fill_parent"
      }
    },
    {
      "view": "ImageView",
      "data": {
        "url": "random.jpg"
      },
      "properties": {
        "width": "fill_parent",
        "height": "500"
      }
    }
  ]
}

I think the problem here is that the JSON structure does not correspond to any strictly specified schema but seems more like an ad-hoc collection of keys and values. For example, (it seems that) depending on the value of the view field in your view description object the data field can be either

  • a JSON array containing other view descriptions (for "Viewpager")
  • a JSON object containing a string called "url" (for "ImageView")
  • a JSON object containing a string called "text" (for "TextView")

So, basically it seems that data can be anything and moreover that you could have an arbitrarily deep tree of nodes where data could be anything at any level in the tree. (It may be different though if, for example, you can always be certain that the top level element is a "Viewpager" that contains one level of sub-views like "ImageView" or "TextView" - if you have any guarantees like that let me know).

In that case I think you are better off parsing the JSON in some other, less strict way (maybe using org.json.JSONArray and org.json.JSONObject ) and then handling all the different cases "manually".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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