How can I proccess Json faster than creating bean objects manually - java

For example, at the moment I am getting a list of restaurants from a Google API. then I have to create a a restaurant class with getters and setters, then I have to create objects of that class and populate them with each field from the returned json manually.
Is there another way to do this quicker than manually doing all the work?

The best thing is to find libraries for that particular API. Failing that, you could consume the JSON without mapping them to Java Beans (i.e. just parse the JSON and work with the parsed JSON by doing parsed.getString("city_name") etc.). Jackson is a good library to do that.
You could also try generating a JSON schema out of the returned JSON, then using that to auto generate Java Beans code, and then use this with a JSON library like Jackson. I tried this once but it seems that you have to fix the generated JSON schema quite a bit as the automatic schema generation tools referenced above isn't very good at the moment.

What I do is just create an object that matches the returned json string and place the values into the object using gson.fromjson()
Object.
public class Return {
private String Status;
private String[] Data;
public Return(String Status, String[] Data){
this.Status=Status;
this.Data=Data;
}
public String getStatus() { return Status; }
public String[] getData() { return Data; }
}
Code to populate Object.
java.lang.reflect.Type listType = new TypeToken<Return>(){}.getType();
Return return2= new Gson().fromJson(myresponse.toString(), listType);

Related

Java Spring omits fields when making a JSON

public class ConnectedEntry {
private EntryInScores scores;
private EntryInValues values;
private String someString;
public ConnectedEntry(EntryInScores scores, EntryInValues values) {
this.scores = scores;
this.values = values;
this.someString = "Adasd";
}
I have an object that looks more or less like this, and I use it as a GET response for my API. scores and values are both database entities. I wanted to add a String to the response with some additional information.
What happens is that the objects are properly turned into a JSON and they show up in the response, but the string is omitted, with no error: it's just not there.
I tried wrapping the string in a wrapper class, but it didn't help.
What could I do?
Usually Spring uses Jackson as the default converter from objects to JSON. In order for Jackson to convert to JSON you must provide getters, so that Jackson can get and convert those values. As I can see in your representation you don't have any getters. Try providing getters for the fields that you wish to convert. Never make fields public!
You can go for creating json object and put the data as key value pair to resolve this issue.
Happy Coding!!!

combine JSON object and JSON array to get another JSON object in Java

I have List<Person> where its JSON output is like:
[{"name":"john","email":"john#email.com"},
{"name":"daniel","email":"daniel#email.com"},
{"name":"thomas","email":"thomas#email.com"}]
and a count of the persons where its JSON format is like: {"number":3}
How can I combine the above two to get the result:
{
"number":3,
"persons":[{"name":"john","email":"john#email.com"},
{"name":"daniel","email":"daniel#email.com"},
{"name":"thomas","email":"thomas#email.com"}]
}
my Java code is jersey2 based JAX-RS application. to make more clear, I have a list of Person fetched from database and i also have an integer variable number. and combine the List and the integer variable to get above result in an efficient and robust way.
Since you are using a framework that already does conversion to JSON automatically, the easiest way would be to just return a new object.
public class Result {
private int number;
private List<Person> persons;
//leaving creation of constructor to you
}
And then just instantiate that object and return it.
When you want to map Object to json directly or want to convert json to object, you can use GSON library . this will give you more flexibility and control.
Download link - http://code.google.com/p/google-gson/
Tutorial link - http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

how to use #JsonProperty in this case - jackson API with lombok

I know how to use #JsonProperty in jackson API but the below case is different.
I've below json snippet.
{"results":[{"uniqueCount":395}
So, to parse with jackson API the above json, I've written below java pojo class.
package com.jl.models;
import lombok.Data;
#Data
public class Results
{
private int uniqueCount;
}
Later, I got to parse below similar json snippet.
{"results":[{"count":60}
Now, the problem here is I'm unable to parse this json with Results class as it expects a string uniqueCount.
I can easily create another java pojo class having count member variable but I've to create all the parent java classes having instance of Results class.
So, is there any way I can customize Results class having lombok behaviour to parse both the json without impacting each others?
Thanks for your help in advance.
You can use Jackson's #JsonAnySetter annotation to direct all unknown keys to one method and there you can do the assignment yourself:
#Data
public class Results
{
private int uniqueCount;
// all unknown properties will go here
#JsonAnySetter
public void setUnknownProperty(String key, Object value) {
if (key.equals("count")) {
uniqueCount = (Integer)value;
}
}
}

Is there any way to create JSON object with keys as upper case?

Project: Android app using REST web service
Using:
Client - Volley
Server API - Jersey
Converter: Gson
This is my first time asking a question here, and i will provide my way of "evading" this code convention. Since i am working on a project where POJO fields are already defined as upper-case (sadly, i cant change that), i had to find a way to fix JSON string and convert it to an instance of uppercase POJO.
So basicaly its: client POJO <--> json object converted to/from gson <--> server POJO
So, lets say that i have a field in Users.class
String USERNAME;
When Jersey sends an instance of via #Produces, it follows the convention of creating JSON and sends an object
{"username": "random_name"}
When it gets converted from JSON via gson.fromJSON, an instance of a client's POJO will get null value for that field (obviously because field is in lower-case in JSONObject).
This is how i managed it by using a method that parses JSONObject and puts each key as upper-case:
public static String fixJSONObject(JSONObject obj) {
String jsonString = obj.toString();
for(int i = 0; i<obj.names().length(); i++){
try{
obj.names().getString(i).toUpperCase());
jsonString=jsonString.replace(obj.names().getString(i),
obj.names().getString(i).toUpperCase());
} catch(JSONException e) {
e.printStackTrace();
}
}
return jsonString;
}
And luckily since gson.fromJSON() requires String (not a JSONObject) as a parameter besides Class, i managed to solve the problem this way.
So, my question would be: Is there any elegant way of making JSON ignore that code convention and create a JSON object with an exact field? In this case:
{"USERNAME": "random_name"}
Jersey uses JAXB internally to marshall beans to xml/json. So you can always use #XmlElement annotation and use name attribute to set the attribute name to be used for marshalling
#XmlElement(name="USERNAME")
String USERNAME;
Just use annotation com.google.gson.annotations.SerializedName
Add in class Users.java:
#SerializedName("username")
String USERNAME;

Create POJOs for every JSON response in different structure?

I used RestTemplate to call some 3rd-Party APIs, and RestTemplate will convert received JSON to java POJO automatically like this:
Result result = restTemplate.getForObject(url, Result.class);
But sometimes the JSON structure is quite simple, such as the two examples:
{"access_token":"abcdefg","expires_in":7200} //only need access_token
{"status":0,"result":{"x":25,"y":46}} //only need "x" and "y"
Should I create POJOs for every JSON response in different structure?
For example, the POJO for the first JSON structure:
public class TokenResult {
private String access_token;
private String expires_in;
/* Getters and Setters */
......
}
For the second JSON structure:
public class CoordResult {
private String status;
private Coordinate result;
/* Getters and Setters */
......
}
public class Coordinate {
private String x;
private String y;
/* Getters and Setters */
......
}
I don't think it is elegant to do so, because some JSON structures are very simple and some are used only once like the "access_token" response.
Any ideas on how to avoid too many simple POJOs?
The example you have there are perfectly fine. Even if it feels you have too many POJOs with property members that are not used this IMO is best and future proof approach. Imagine in near future you need to implement functionality that will require access to TokenResult.getExpiresIn() this would mean you would still end up refactoring the base POJO and adding that method and class member.
In similar example with the CoordResult I see the status as a quite important property that would need checking once the response is received so mapping that to a class member in a POJOs is very good idea.
This will make your code more resilient and also predictive with well defined structure and encapsulating all available data from the response.
Though if you have similar responses in terms of context and structure you can always extend a base POJO and add the relevant class members to a child class.
Another benefit is that this all makes the client code easy to read as we can tell what we expect from the response objects and that can be used in different implementations many of which may not applicable and visible now.
If you decide you don't need all properties of a JSON response you can still use #JsonIgnoreProperties annotation on the class and it'll exclude any unknown elements from the JSON mapping.
EX:
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class TokenResult {
private String access_token;
// you don't need this
// private String expires_in;
}
If you're looking for just some values from the response you could try the org.json package ( http://www.json.org/javadoc/ ). It has methods to access values in a JSON response.
String jsonStr = "{\"access_token\":\"abcdefg\",\"expires_in\":7200}";
String accessToken = new JSONObject(jsonStr).getString("access_token");
This approach gets a little more tricky trying to nested values.

Categories

Resources