Recover Json field 2 level of array gson or Jackson

0

I have a Json with the following format:

{
  "resultado": [
    {
      "columa": [
        "p"
      ],
      "datos": [
        {
          "row": [
            {
              "oficina": "0000",
              "entidad": "1234",
              "nombre": "nombre persona"
            }
          ],
          "meta": [
            {
              "id": 4700925,
              "type": "node",
              "deleted": false
            }
          ]
        }
      ]
    }
  ],
  "errors": [],
  "responseTime": 84
}

How can I recover the data office and entity?

    
asked by Alrio 01.08.2017 в 10:52
source

1 answer

0

With this you recover the 2 fields that you want:

String t = "{ \"resultado\": [{\"columa\": [\"p\"],\"datos\": [{\"row\": [{\"oficina\": \"0000\",\"entidad\": \"1234\"," +
            "\"nombre\": \"nombre persona\"}],\"meta\": [{\"id\": 4700925,\"type\": \"node\",\"deleted\": false}]}]}],\"errors\": [],\"responseTime\": 84}\"" ;

    JSONObject js = null;

    String oficina="";
    String entidad="";

    try {
        js = new JSONObject(t);
        JSONArray res = (JSONArray) js.get("resultado");

        JSONObject jsDat = (JSONObject) res.get(0);

        JSONArray jsDatArr = (JSONArray) jsDat.getJSONArray("datos");

        JSONObject jsRow = (JSONObject) jsDatArr.get(0);

        JSONArray jsRowArr = (JSONArray) jsRow.get("row");

        JSONObject jsFin = (JSONObject) jsRowArr.get(0);

        oficina = jsFin.getString("oficina");
        entidad = jsFin.getString("entidad");
    }catch(Exception e)
    {
        log.Info(e.getMessage());
    }

This works although it is not very elegant, having several levels has to go through one by one.

If you need to have access to all the data I would recommend that you create your result object to deserialize the JSon in an object, it is much easier to go through it later, but if you only want those 2 data with that code, you take them out.

    
answered by 01.08.2017 / 13:57
source