echobravocharlie
echobravocharlie

Reputation: 55

How to convert a JSON file to a readable object in Java

I am new to Java. I have the following .json file with the following kind of contents:

{
  "res": [
    {
      "test1": "323dfer",
      "test2": "adqdcr2c"
    },
    {
      "test1": "23cr2c2c",
      "test2": "23rv2rvc"
    }
  ]
}

And currently I am accessing this file like so:

InputStream jsonfile= this.getClass().getClassLoader().getResourceAsStream("test.json");

assert jsonfile!= null;
ObjectMapper mapper = new ObjectMapper();
Map jsonMap = mapper.readValue(jsonfile, Map.class);

Object records = jsonMap.get("res");
System.out.println(records);

which results in this output:

[{test1=323dfer, test2=adqdcr2c}, {test1=23cr2c2c, test2=23rv2rvc}]

However, I am now not sure how to access the second object in the array and loop trough the keys, e.g. test1 and test2, etc.

I am wondering if anyone can help with this?

Upvotes: 0

Views: 902

Answers (1)

bekirduran
bekirduran

Reputation: 161

Firstly you should create an entity.

Like below:

private class TestObject{
public String testName;

public TestObject(String testName) {
    this.testName= testName;
}

}

Second: You should add Google GSON (Maven) dependency. Its very usefull library. You can use this link.

Finally: Create a Gson object then call its convertion method.

Gson gson = new Gson();

TestObject testObject = gson.fromJson(jsonfile, TestObject.class);
System.out.println(testObject.testName);

Upvotes: 2

Related Questions