Let's say I have a file sample.json which contains an array of objects as shown below.
[ {Name: "ABC", "email" : "[email protected]", "city" : "NewYork"}, {Name: "XYZ", "email" : "[email protected]", "city" : "NewJersey"}]
I am using TestNG framework and GSON library to parse JSON.
Below is the class where I want to parse JSON object wise. My aim is to filter the object by its name in array and return only that object. I am using Streaming API to avoid returnig all the data at once present in json file.
public class JSON{
private JsonObject jsonObject;
@Test
public void readJSON(){
getJSONObject("C:\\..\\sample.json", "ABC");
readData("email");
}
public JsonObject getJSONObject(fileName, Name){
JsonReader jsonReader = new JsonReader(new FileReader(fileName));
jsonReader.beginArray();
while (jsonReader.hasNext()){
str = jsonReader.nextString();
If (str.equals(Name)){
System.out.println("Found Name");
// To get the object - we can use fromJson(jsonReader, Person.class),
// where Person.class defines all the json variables as class variables.
// But I want to use JsonParser or something like that to return just this object which has the Name "ABC"
}
}
} }
Reason why I don't want to create a Person class and use fromJSON because I use this function for different types of JSON strings. So I don't prefer to create different classes for different strings. I want to use something else instead which just returns the required object. Also I am not sure how to iterate through the array using hasNext() of Streaming API method to find the required object.
Any inputs are appreciated. Thank you.