0

I have the following JSON data:

JSON:

[{
"valInternalCode": "NE",
"valMinimumInputString": "NE",
"valExternalRepresentation": "Northeast",
"valActionCode1": "1",
"valActionCode2": null,
"valActionCode3": null,
"valActionCode4": null,
"id": {
    "valcodeId": "X.LOCATION",
    "pos": 1
},
"uniqueId": "X.LOCATION-1",
"caption": "Northeast"
}, {
"valInternalCode": "NW",
"valMinimumInputString": "NW",
"valExternalRepresentation": "Northwest",
"valActionCode1": "1",
"valActionCode2": null,
"valActionCode3": null,
"valActionCode4": null,
"id": {
    "valcodeId": "X.LOCATION",
    "pos": 2
},
"uniqueId": "X.LOCATION-2",
"caption": "Northwest"

}

I am able to parse it and create a Map from the data like so:

Gson gson = new Gson();

Type collectionType = new TypeToken<Collection<Map>>(){}.getType();
Collection<Map> dataCollection = gson.fromJson(jsonString.toString(), collectionType);

I can then iterate through it and get a value that I need using the Key like so:

 iterator.next().get("valInternalCode");

What I am struggling with is how to get something that is inside of the id field:

"id": {
"valcodeId": "X.LOCATION",
"pos": 2
},

I am using Hibernate to get the data from a non normalized Oracle database (that is why hibernate creates the id field the way it does)

EDIT:

My attempt at an ugly way of doing it. Basically looping within the loop:

while (valIterator.hasNext()) {
  Map currentVal = valIterator.next();
  String valId = "";

  Collection<Map> idVal = (Collection<Map>) currentVal.get("id");
  Iterator<Map> valIdIterator = idVal.iterator();

  while (valIdIterator.hasNext()) {
    Map valIdCurrentVal = valIdIterator.next();

    valId = valIdCurrentVal.get("valcodeId").toString();
  }
}

Getting a ClassCastException when I try to cast currentVal.get("id") to a Collection

Mr Man
  • 1,498
  • 10
  • 33
  • 54
  • What have you tried? Was an exception thrown? – Cardinal System Nov 06 '17 at 17:12
  • Possible duplicate of https://stackoverflow.com/questions/443499/convert-json-to-map – Rafiq Nov 06 '17 at 17:14
  • @CardinalSystem Well the only thing I have tried is to iterate inside the while loop of my other iterator, but am wondering if there is another way. I am in the process of getting that code "working" but will post again if I do – Mr Man Nov 06 '17 at 17:29
  • @CardinalSystem post edited, thanks. – Mr Man Nov 06 '17 at 17:44
  • I am guessing that you dont have to iterate over the id, since its a JSONObject, you should be able to fetch values out from it. – ajc Nov 29 '17 at 17:46

0 Answers0