Parsing the nested JSON Array using Jackson library in java - java

I would like to know how to parse the following JSON using jackson library in java to construct the URI like http://api.statdns.com/google.com/cname
{
"status": {
"status": 200,
"msg": "SUCCESS"
},
"apicalls": [
{
"API": {
"method": "get",
"success": "200",
"baseURL": "http://api.statdns.com/",
"param1": "google.com/",
"param2": "cname",
"continue_on_fail": "1",
"add_header2": "'Accept', 'application/json'",
"add_header1": "'Content-Type', 'application/json'",
"client_id": "101"
},
"id": 1385
}
]
}
I have written bad code to parse the above json array. Following is the code i used,
public void parseJSON(String json) {
try{
JsonFactory factory = new JsonFactory();
JsonParser parser;
parser = factory.createJsonParser(json);
parser.setCodec(new ObjectMapper()); // to avoid IllegalStateException
JsonToken current;
current = parser.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}
while (parser.nextToken() != JsonToken.END_OBJECT) {
String fieldName = parser.getCurrentName();
// Move from field name to field value
current = parser.nextToken();
if (fieldName.equals("APIcalls")) {
JsonNode node = parser.readValueAsTree();
JsonNode currentJson = node.findValue("API");
System.out.println("Current JSON :: " + currentJson);
JsonNode url = currentJson.get("baseURL");
JsonNode param1 = currentJson.get("param1");
JsonNode param2 = currentJson.get("param2");
String baseURL = url.asText();
String params1 = param1.asText();
String params2 = param2.asText();
String uri = baseURL + params1 + params2;
System.out.println("URL :: " + uri);
initiateRESTCall(uri);
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Could anyone help me to know parsing the JSON using jackson? Help is highly appreciated.

If you are using jackson library, then you should go something like this:
I am using response from http://api.statdns.com/google.com/cname
public void parseJSON(String json) {
JSONObject parse = new JSONObject(data);
if(parse.get("question") instanceof JSONObject){
JSONObject questionJson = (JSONObject) parse.get("question");
System.out.println("Name"+questionJson.getString("name"));
System.out.println("Type"+questionJson.getString("type"));
System.out.println("Class"+questionJson.getString("class"));
}
else if(parse.get("question") instanceof JSONArray){
JSONArray questionJson = (JSONArray) parse.get("question");
String[] nameAttrib=new String[questionJson.length()];
String[] typeAttrib=new String[questionJson.length()];
String[] classAttrib=new String[questionJson.length()];
for(int i=0;i<questionJson.length();i++){
JSONObject questionJsonData=(JSONObject)questionJson.get(i);
nameAttrib[i]=questionJsonData.getString("name");
typeAttrib[i]=questionJsonData.getString("type");
classAttrib[i]=questionJsonData.getString("class");
System.out.println("Name: "+nameAttrib[i]);
System.out.println("Type: "+typeAttrib[i]);
System.out.println("Class: "+classAttrib[i]);
}
}
else if (parse.get("question").equals(null)){
System.out.println("question"+null);
}
}
Here I am doing for "question" only, similarly you can do other as well say "answer", "authority" in case url you have mentioned http://api.statdns.com/google.com/cname.
Hopefully it helps you with your problem..!!!!

If you are confident in the JSON not changing, a quick and dirty way to simplify your code is to use JSON Pointers.
// prefer injecting your project's ObjectMapper
private static final ObjectMapper om = new ObjectMapper();
public void parseJSON(String json) throws IOException {
JsonNode jsonNode = om.readTree(json);
String uri = new StringBuilder(jsonNode.findValue("baseURL").asText())
.append(jsonNode.findValue("param1").asText())
.append(jsonNode.findValue("param2").asText())
.toString();
initiateRESTCall(uri);
}
This becomes vulnerable if multiple apicalls entries are returned.

I don't know JACKSON library but I think it is similar to GSON. You just have to make some POJO and the library will take care of filling the fields for you.
For instance to convert your string to MyJSONClass use the following classes :
class Status {
int status;
String msg;
}
class APIClass {
String method;
String success;
String baseURL;
String param1;
String param2;
String continue_on_fail;
String add_header2;
String add_header1;
String client_id;
}
class APICall {
APIClass API;
int id;
}
class MyJSONClass {
Status status;
List<APICall> apicalls;
}
This set of classes could be transformed to JSON with JACKSON library (thanks to this stackoverflow answer) like that:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

Related

Any method of passing the Json data in URL format using JSONObject?

I create a java URL class which contain my Json data and have some function to obtain back my json data for doing some data comparison, I found out it's might not support by JSONObject for passing the data into the JSONObject. Do I need to use JSONArray in my case because my JSON data have array structure as well?
try
{
JSONObject obj = new JSONObject ();
obj.readJsonFromUrl(theUrl);
System.out.println(obj.toString());
}
catch(MalformedURLException e)
{
System.out.print("your problem here ...1");
}
}
else
{
System.out.print("Can't Connect");
}
I am sure that this is the place give me the error message because it return me this error in my compiler
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method readJsonFromUrl(URL) is undefined for the type JSONObject
there are also some warning message for that the JSONObject readJsonFromUrl method
private static JSONObject readJsonFromUrl(URL theUrl) throws IOException, JSONException {
Anyone can provide me the explaination of how the JSON data work in java? I saw quite number of Java class for JSON which make me confuse for it such as JSONObject, JSONArray , JSONValue. I search some information online but I also not very clear about it since I am very new to JSON data processing This is my sample json data and the data I need is scan_result only
{
"data_id":"a71a3c2588c6472bb4daea41a0b58835",
"file_info":{
"display_name":"",
"file_size":242,
"file_type":"Not available",
"file_type_description":"Not available",
"md5":"aa69ba384f22d0dc0551ace2fbb9ad55",
"sha1":"09ceb54e65df3d3086b222e8643acffe451a6e8a",
"sha256":"dcb46d6ae2a187f789c12f19c44bbe4b9a43bd200a3b306d5e9c1fcf811dc430",
"upload_timestamp":"2016-11-18T09:09:08.390Z"
},
"process_info":{
"blocked_reason":"",
"file_type_skipped_scan":false,
"post_processing":{
"actions_failed":"",
"actions_ran":"",
"converted_destination":"",
"converted_to":"",
"copy_move_destination":""
},
"profile":"File scan",
"progress_percentage":100,
"result":"Allowed",
"user_agent":""
},
"scan_results":{
"data_id":"a71a3c2588c6472bb4daea41a0b58835",
"progress_percentage":100,
"scan_all_result_a":"No Threat Detected",
"scan_all_result_i":0,
"scan_details":{
"Ahnlab":{
"def_time":"2016-11-08T15:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":1,
"threat_found":""
},
"Avira":{
"def_time":"2016-11-08T00:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":133,
"threat_found":""
},
"ClamAV":{
"def_time":"2016-11-08T10:28:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":94,
"threat_found":""
},
"ESET":{
"def_time":"2016-11-08T00:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":38,
"threat_found":""
}
},
"start_time":"2016-11-18T09:09:08.405Z",
"total_avs":4,
"total_time":250
},
"vulnerability_info":{
}
}
As mentioned here, there are many ways to solve this. Either you have to implement the read, parse operations yourself (#Roland Illig 's answer)
//you have to implement the readJSON method
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
Or you could use a library. The most well-known and widely used libraries are jackson and gson.
The big picture is that you try to "map" your json Object to a class.
You have your json file:
{
"id":1,
"name":"eirini",
"hobbies":["music","philosophy","football"]
}
and a class that represents this file and will store the values (depending on the library that you use there might be different requirements, for example getters, setters etc..)
public class Person {
public int id;
public String name;
public List<String> hobbies = new ArrayList<String>();
public String toString() {
return name +" has the id: " + id + " the following hobbies" + hobbies.get(0) + " " + hobbies.get(2);
}
}
Finally in your main method:
public static void main(String[] args) throws IOException, ParseException {
ObjectMapper mapper = new ObjectMapper();
InputStream input = this.getClass().getResourceAsStream(FILE); //read your file. There are many ways to achieve this.
ObjectMapper mapper = new ObjectMapper(); // just need one
Person eirini = mapper.readValue(input, Person.class);
System.out.println(eirini.toString());
You cannot pass json in url, you can pass it in body. Writing Json to stream body and post it using regular java method.
Here is oracle community url of explanation of your problem.
Required Jar can be downloaded from here.
Test Code Follows:
URL url = new URL("https://graph.facebook.com/search?q=java&type=post");
try (InputStream is = url.openStream();
JsonReader rdr = Json.createReader(is)) {
JsonObject obj = rdr.readObject();
JsonArray results = obj.getJsonArray("data");
for (JsonObject result : results.getValuesAs(JsonObject.class)){
System.out.print(result.getJsonObject("from").getString("name"));
System.out.print(": ");
System.out.println(result.getString("message", ""));
System.out.println("-----------");
}
}

Firebase Android: how do I access params nested in data via RemoteMessage?

via this shape:
{
"to": "000",
"priority": "high",
"data": {
"title": "A Title",
"message": "A Message",
"link": {
"url": "http://www.espn.com",
"text": "ESPN",
}
}
}
how can I access "url" and "text"?
String messageLink = remoteMessage.getData().get("link");
gets me:
{"text":"ESPN","url":"http://www.espn.com"}
but how do I drill deeper?
remoteMessage.getData().get("link").get("text");
doesnt quite work... I have also attempted JSONObject:
JSONObject json = new JSONObject(remoteMessage.getData());
JSONObject link = json.getJSONObject("link");
but this gives me try catch errors...
Any help and direction as always is greatly appreciated!
I would use gson and define a model class. The remote message gives you a Map<String, String> and their is no matching constructor for creating a json object.
Add gson to your build.xml:
compile 'com.google.code.gson:gson:2.5'
Create a notification model:
import com.google.gson.annotations.SerializedName;
public class Notification {
#SerializedName("title")
String title;
#SerializedName("message")
String message;
#SerializedName("link")
private Link link;
public String getTitle() {
return title;
}
public String getMessage() {
return message;
}
public Link getLink() {
return link;
}
public class Link {
#SerializedName("url")
String url;
#SerializedName("text")
String text;
public String getUrl() {
return url;
}
public String getText() {
return text;
}
}
}
Deserialize a notification object from the remote message.
If all your custom keys are at the top level:
Notification notification = gson.fromJson(gson.toJson(remoteMessage.getData()), Notification.class);
If your custom json data is nested in a single key for example "data" then use:
Notification notification = gson.fromJson(remoteMessage.getData().get("data"), Notification.class);
Note in this simple case the #SerializedName() annotations are unnecessary since the field names exactly match the keys in the json, but if you for example have a key name start_time but you want to name the java field startTime you would need the annotation.
As simple as that:
String linkData = remoteMessage.getData().get("link");
JSONObject linkObject = new JSONObject(linkData);
String url = linkObject.getString("url");
String text = linkObject.getString("text");
Of course, together with proper error handling.
Faced this issue when migrating from GCM to FCM.
The following is working for my use case, so perhaps it will work for you.
JsonObject jsonObject = new JsonObject(); // com.google.gson.JsonObject
JsonParser jsonParser = new JsonParser(); // com.google.gson.JsonParser
Map<String, String> map = remoteMessage.getData();
String val;
for (String key : map.keySet()) {
val = map.get(key);
try {
jsonObject.add(key, jsonParser.parse(val));
} catch (Exception e) {
jsonObject.addProperty(key, val);
}
}
// Now you can traverse jsonObject, or use to populate a custom object:
// MyObj o = new Gson().fromJson(jsonObject, MyObj.class)

Spring Social Facebook: How to get big photo from Post?

The Post object has a property getPicture(). This contains an url to a very small (130 × 130) image.
How to get the big picture of a Facebook post?
Sample url:
https://scontent.xx.fbcdn.net/v/t1.0-0/s130x130/13173717_10209376327474891_7842199861010585961_n.jpg?oh=d244df2db666e1d3be73cb7b76060337&oe=57A64C44
It does not help to replace the s130x130 in the url because that won't work in the new Graph API.
I tried to use graphApi.mediaOperations() but I don't see a method that accepts a postId. There is graphApi.mediaOperations().getPhotos(objectID) but this objectID has to be an AlbumID or UserID according to the documentation and this method throws an exception:
org.springframework.social.UncategorizedApiException: (#100) Tried accessing nonexisting field (photos) on node type (Photo)
Edit: I found something that works:
byte[] photo = graphApi.mediaOperations().getAlbumImage(post.getObjectId(), ImageType.NORMAL);
But now I get a byte[] instead of an url so now I have to store the image somewhere :(
i didn't get any direct method to fetch full_picture of Facebook post using Spring Social framework. I used Facebook's graph API to get full picture. I am adding code for references only. you need to be customize as per you need.
FacebookTemplate facebook = new FacebookTemplate("<fb token>");
String[] ALL_POST_FIELDS = { "id", "actions", "admin_creator", "application", "caption", "created_time", "description", "from", "icon",
"is_hidden", "is_published", "link", "message", "message_tags", "name", "object_id", "picture", "full_picture", "place", "privacy",
"properties", "source", "status_type", "story", "to", "type", "updated_time", "with_tags", "shares", "likes.limit(1).summary(true)" };
URIBuilder uriBuilder = URIBuilder.fromUri(facebook.getBaseGraphApiUrl() + request.getAccountId() + "/posts");
uriBuilder = uriBuilder.queryParam("limit", String.valueOf(request.getRecordCount()));
uriBuilder.queryParam("fields", org.springframework.util.StringUtils.arrayToCommaDelimitedString(ALL_POST_FIELDS));
URI uri = uriBuilder.build();
LOGGER.info("facebook URL :{} ", uri);
JsonNode jsonNode = (JsonNode) facebook.getRestTemplate().getForObject(uri, JsonNode.class);
LOGGER.debug("facebook URL :{}, response: {} ", uri, jsonNode);
// you can cast jsonnode as required into your format or below line can be used to cast into PagedList<Post> format
PagedList<Post> posts = new DeserializingPosts().deserializeList(jsonNode, null, Post.class, true);
Then jsonNode code be cast into your required format. or you can also cast it to PagedList<Post> using below DeserializingPosts class.
#Component
public class DeserializingPosts extends AbstractOAuth2ApiBinding {
private ObjectMapper objectMapper = new ObjectMapper();
private static final Logger LOGGER = Logger.getLogger(DeserializingPosts.class);
public <T> PagedList<T> deserializeList(JsonNode jsonNode, String postType, Class<T> type, boolean accountFlag) {
JsonNode dataNode = jsonNode.get("data");
return deserializeList(dataNode, postType, type);
}
public <T> PagedList<T> deserializeList(JsonNode jsonNode, String postType, Class<T> type) {
List posts = new ArrayList();
for (Iterator iterator = jsonNode.iterator(); iterator.hasNext();) {
posts.add(deserializePost(postType, type, (ObjectNode) iterator.next()));
}
if (jsonNode.has("paging")) {
JsonNode pagingNode = jsonNode.get("paging");
PagingParameters previousPage = PagedListUtils.getPagedListParameters(pagingNode, "previous");
PagingParameters nextPage = PagedListUtils.getPagedListParameters(pagingNode, "next");
return new PagedList(posts, previousPage, nextPage);
}
return new PagedList(posts, null, null);
}
public <T> T deserializePost(String postType, Class<T> type, ObjectNode node) {
try {
if (postType == null) {
postType = determinePostType(node);
}
node.put("postType", postType);
node.put("type", postType);
MappingJackson2HttpMessageConverter converter = super.getJsonMessageConverter();
this.objectMapper = new ObjectMapper();
this.objectMapper.registerModule(new FacebookModule());
converter.setObjectMapper(this.objectMapper);
return this.objectMapper.reader(type).readValue(node.toString());
} catch (IOException shouldntHappen) {
throw new UncategorizedApiException("facebook", "Error deserializing " + postType + " post" + shouldntHappen.getMessage(),
shouldntHappen);
}
}
private String determinePostType(ObjectNode node) {
if (node.has("type")) {
try {
String type = node.get("type").textValue();
Post.PostType.valueOf(type.toUpperCase());
return type;
} catch (IllegalArgumentException e) {
LOGGER.error("Error occured while determining post type: " + e.getMessage(), e);
return "post";
}
}
return "post";
}
}
use ImageType.LARGE instead of ImageType.NORMAL
it returns CustomMultipartFile

Java - Json deserialize data []

I am new to stackoverflow.
I am creating an Java application which it will get data from a web server. The data is in json format. Example"
[
{
"item_name": "Adame",
"item_type": "Special",
"item": "Chestplate",
"item_min_lvl": "50",
"enchantment": {
"health": "0.3",
"dam": "24%",
"life": "0.1",
"xp": "24%",
"loot": "22%"
},
"def": "73"
},
{
"item_name": "Sticks'",
"item_type": "Unique",
"item": "Stick",
"item_min_lvl": "4",
"enchantment": {
"health": "0.6",
"mana": "1",
"dam": "12%",
"life": "0.3",
"xp": "17%",
"loot": "17%"
},
"min_dam": "39",
"max_dam": "34"
}
]
I know how to deserialize json using Gson. As you can see, it's started with [. I never deserialize this case before. Also, the json data is not the same(e.g. enchantment). I also searched in Google but I can't find any similar case. Can anyone help me with the code?
Try with this code. You will get the answer of your question. It's an List with 2 items.
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(new File("resources/json1.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<MyJSON>>() {
}.getType();
List<MyJSON> list = gson.fromJson(builder.toString(), listType);
// you can try this form as well
// MyJSON[] list = gson.fromJson(builder.toString(), MyJSON[].class);
for (MyJSON json : list) {
System.out.println(json.toString());
}
...
class MyJSON {
String item_name;
String item_type;
String item;
String item_min_lvl;
Enchantment enchantment;
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("\nitem_name:").append(item_name);
builder.append("\nitem_type:").append(item_type);
builder.append("\nitem:").append(item);
builder.append("\nitem_min_lvl:").append(item_min_lvl);
builder.append("\n\nEnchantment Details:");
builder.append("\nhealth:").append(enchantment.health);
builder.append("\ndam:").append(enchantment.dam);
builder.append("\nlife:").append(enchantment.life);
builder.append("\nxp:").append(enchantment.xp);
builder.append("\nloot:").append(enchantment.loot);
return builder.toString();
}
}
class Enchantment {
String health;
String dam;
String life;
String xp;
String loot;
}
output:
item_name:Adame
item_type:Special
item:Chestplate
item_min_lvl:50
Enchantment Details:
health:0.3
dam:24%
life:0.1
xp:24%
loot:22%
item_name:Sticks'
item_type:Unique
item:Stick
item_min_lvl:4
Enchantment Details:
health:0.6
dam:12%
life:0.3
xp:17%
loot:17%
EDIT
The structure of each entry is not same hence you can't use POJO for this type of JSON.
Simply use ArrayList<Map<String, Object>> and access the value based on key from the map.
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Map<String, Object>>>() {
}.getType();
ArrayList<Map<String, Object>> list = gson.fromJson(builder.toString(), listType);
for (Map<String, Object> json : list) {
for (String key : json.keySet()) {
System.out.println(key + ":" + json.get(key));
}
System.out.println("===========");
}
output:
item_name:Adame
item_type:Special
item:Chestplate
item_min_lvl:50
enchantment:{health=0.3, dam=24%, life=0.1, xp=24%, loot=22%}
def:73
===========
item_name:Sticks'
item_type:Unique
item:Stick
item_min_lvl:4
enchantment:{health=0.6, mana=1, dam=12%, life=0.3, xp=17%, loot=17%}
min_dam:39
max_dam:34
===========
This is actually valid in Java and with GSON:
YourObject[] locs = gson.fromJson (someJsonString, YourObject[].class);
It'll parse and return an array of YourObject. Just create Java Classes that represent your JSON objects, and replace the placeholders as necessary.
EDIT:
As Braj said before, you can create a fully formed POJO, including the other, (non-symmetrical) attributes (I'm borrowing the code from from Braj's answer here):
//... snip ...
class MyJSON
{
String item_name;
String item_type;
String item;
String item_min_lvl;
Enchantment enchantment;
// Heres the other attributes
String min_dam;
String max_dam;
}
//... snip ...
GSON will parse it and set the values to null if they aren't provided in the original JSON.
However, from the other question, it seems that the JSON (Java - JSON Parser Error) for enchantment is provided inconsistently, so this will cause issues. I would recommend sending JSON for enchantment as an array for consistency, then you could structure your POJO as:
//... snip ...
class MyJSON
{
String item_name;
String item_type;
String item;
String item_min_lvl;
Enchantment[] enchantment;
// Heres the other attributes
String min_dam;
String max_dam;
}
//... snip ...

Interpreting and reading JSON with GSON

I'm having trouble trying to make sense of this JSON string.
{
"results":[
{
"user":{
"gender":"female",
"name":{
"title":"miss",
"first":"taylor",
"last":"anderson"
},
"location":{
"street":"3645 dogwood ave",
"city":"roseburg",
"state":"new hampshire",
"zip":"20963"
},
"email":"taylor.anderson49#example.com",
"username":"heavyduck595",
"password":"liverpool",
"salt":"UK`o;9a_",
"md5":"6c8db0305b4591d8d9820d9f8edfd162",
"sha1":"906df4c09f3a87899666cb57bf974bd9b1950ea6",
"sha256":"3b12f5e51688578f845bef8ae1750d3e263c2010691010a80ce632a6b2323c03",
"registered":"1359027425",
"dob":"16243995",
"phone":"(934)-888-7068",
"cell":"(727)-467-8384",
"SSN":"697-20-6143",
"picture":"http://api.randomuser.me/0.3/portraits/women/30.jpg"
},
"seed":"5eaf02877746c7e",
"version":"0.3"
}
]
}
It's the first time I've really used JSON and want to try and interpret it appropriately. This is the code i have thus far:
static class Results{
String results;
}
static class User{
String gender;
String name;
String location;
List<Results> items;
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
public void larry() throws Exception{
String json = readUrl("http://api.randomuser.me/");
System.out.println(json);
Gson gson = new Gson();
User page = gson.fromJson(json, User.class);
System.out.println(page.name);
for (Results item : page.items)
System.out.println(" " + item.results);
}
There is nothing particularly complicated about JSON, or mapping it to your own Java classes. You just have to understand the basic structure.
Your JSON is an object that has exactly one field; results. This is what {} means:
{ "results": ... }
That field holds an array. That's the [].
{ "results": [ ... ] }
That array holds another object (presumably you'd have more than one in an array, but the JSON you've posted just has one). That object has three fields, one of which ("user") holds another object with the other two being strings.
To map that to your own classes, you simply make them look like that JSON:
class JsonResult {
List<Result> results; // JSON arrays map to Java Lists
}
class Result {
User user;
String seed;
String version;
}
class User {
String gender;
Name name;
// and so on ...
}
class Name {
String title;
String first;
String last;
}
And so forth. You build classes to match the objects (again, denoted by {}) in the JSON, and structure everything accordingly.
As #HotLicks notes in his comment, you can decide not to map to Java classes and use a "clean" parser. In fact, Gson offers this with it's JsonParser class. This will just parse the JSON to a tree from which you can extract the info you want:
JsonElement element = new JsonParser().parse(yourJsonString);
From there you can access the JSON structure using the field names:
JsonObject root = element.getAsJsonObject();
JsonArray array = root.getAsJsonArray("results");
By accessing the JSON structure you can get to whatever you want.

Categories