Home > Mobile >  How to handle JsonObject to own Object
How to handle JsonObject to own Object

Time:06-05

Now i take JsonObject from API like this:
Its XML object converted to JsonObject.

"Details": {
                        "row": [
                            {
                                "item": [
                                    {
                                        "name": "Account",
                                        "value": 12521512
                                    },
                                    {
                                        "name": "ACCNO",
                                        "value": 4214
                                    },
                                    {
                                        "name": "Number",
                                        "value": 5436
                                    }
    ]
    },
    "item": [
                                    {
                                        "name": "Account",
                                        "value": 5789678
                                    },
                                    {
                                        "name": "ACCNO",
                                        "value": 6654
                                    },
                                    {
                                        "name": "Number",
                                        "value": 0675
                                    }
    ]
    },

But i need convert this object and send like this:

 {
  "Details": {
    "row": [
      {
        "Account": 12521512,
        "ACCNO": 4214,
        "Number": 12412421
      },
      {
        "Account": 5789678,
        "ACCNO": 6654,
        "Number": "0675"
      }
    ]
  }
}

I have rows more than 1000, i need faster way to handle. How to handle, please help me

CodePudding user response:

You could use the JSON-java library to parse your input and transform it to your desired format. Something like this works but you may need to adjust it to your needs:

JSONObject jsonObject = new JSONObject(json); // Load your json here
JSONObject result = new JSONObject("{\"Details\": {\"row\": []}}");
for (Object row : jsonObject.getJSONObject("Details").getJSONArray("row")) {
    if (!(row instanceof JSONObject)) continue;
    Map<Object, Object> values = new HashMap<>();
    for (Object item : ((JSONObject) row).getJSONArray("item")) {
        if (!(item instanceof JSONObject)) continue;
        values.put(((JSONObject) item).get("name"), ((JSONObject) item).get("value"));
    }
    result.getJSONObject("Details").getJSONArray("row").put(values);
}

// Now result is in your format
  • Related