trebleCode
trebleCode

Reputation: 2308

Java - JSON Parsing to and Fro

I have been combing over multiple approaches with different JSON libraries, and cannot seem to find an elegant way to convert to and from with my JSON file in testing.

JSON file looks like this:

[
  {
    "LonelyParentKey": "Account",
    "ProcessNames": [
      {"Name":  "ProcessOne",
      "Sequence": "1"
      },
      {
        "Name": "ProcessTwo",
        "Sequence": "2"
      },
      {
        "Name": "ProcessThree",
        "Sequence": "3"
      },
      {
        "Name": "ProcessFour",
        "Sequence": "4"
      }
    ]
  }
]

In a QAF-based test using TestNG, am trying to import the values of the "ProcessName" key like this:

  String lonelyParentKey = (String) data.get("LonelyParentKey");
  ArrayList processNames = (ArrayList) data.get("ProcessNames");

I've seen that in the framework I'm using, I have multiple JSON library options, have been trying to use GSON after reading other SO posts.

So, next in the test code:

  Gson gson = new Gson();
  JSONArray jsa = new JSONArray(processNames);

What I am attempting to to create an object that contains 4 child objects in a data structure where I can access the Name and Sequence keys of each child.

In looking at my jsa object, it appears to have the structure I'm after, but how could I access the Sequence key of the first child object? In the REPL in IntelliJ IDEA, doing jsa.get(0) gives me "{"Name": "ProcessOne","Sequence": "1"}"

Seems like a situation where maps could be useful, but asking for help choosing the right data structure and suggestions on implementing.

TIA!

Upvotes: 0

Views: 63

Answers (2)

Ulf Jaehrig
Ulf Jaehrig

Reputation: 749

Any reason to not use DTO classes for your model?

e.g.

class Outer {
    String lonelyParentKey;
    List<Inner> processNames;

    // getter/setter
}

and

class Inner {
    String name;
    String sequence;

    // getter/setter
}

now your library should be able to deserialize your JSON string into a List. I have been using Jackson instead of GSON, but it should be similar in GSON:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
List<X> x = objectMapper.readValue(json, new TypeReference<List<X>>() {});

Upvotes: 1

Simon
Simon

Reputation: 3264

Not sure which library you're using, but they all offer pretty much the same methods. JSONArray looks like org.json.JSONArray, so that would be

JSONArray jsa = new JSONArray(processNames);
int sequenceFirstEntry = jsa.getJSONObject(0).getInt("Sequence");

Some JsonArray implementations also implement Iterable, then this also works

JSONArray jsa = new JSONArray(processNames);
for (JSONObject entry : jsa) {
    int sequenceFirstEntry = entry.getInt("Sequence");    
}

Upvotes: 1

Related Questions