Unable to parse JSON file using GSON library

437 views Asked by At

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"
      }
    }
  ]
}
1

There are 1 answers

0
david.mihola On

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".