JSON to Objects in java? - java

Does anyone know if there is the ability to generate objects for JSON data? I know there are generic JSON object libraries, but I am looking for more specific - similar to how jaxb can convert SOAP definitions or XSDs into an object model. I know there would need to be some sort of JSON definition file (which I do not know if that concept even exists within JSON), but I feel like that would be a lot more beneficial. Think:
Generic case:
genericJsonObect.get("name");
Specific case:
specificJsonObject.getName();

Jackson and XStream have the ability to map json to POJOs.

Do you want the .java source file to be generated for you? Or to map exiting java beans to JSON objects?
If the former, there is no such a library ( that I'm aware of ) if the later, Google GSON is exactly what you need.
From the samples:
class BagOfPrimitives {
public int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
System.out.println( json );
Prints
{"value1":1,"value2":"abc"}
( Deserialization )
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
System.out.println( obj2.value1 ) ; // value1 is 1

I think the Jackson data mapper can do what you need. It can serialize/deserialize a real Java object into a Json tree.
But others API should also work :
Sojo
FlexJSON
Gson

I am not familiar of such code generation project, although I am sure many Java JSON library projects would be interested in having such thing. Main issue is that there is good Schema language for JSON that would allow code generation; JSON Schema only works for validation.
However: one possibility you could consider is to just use JAXB to generate beans, and then use Jackson to use those beans. It has support for JAXB annotations so you would be able to work with JSON and beans generated.

I have found this site very useful.
http://jsongen.byingtondesign.com/ and have used it in our projects.

Related

Convert Json to a java object

What is the way to generate a Java object with get and set methods?
You should write a java bean with properties maching the JSON key's, from that point since you already have a reader its a simple as
YourObject obj = gson.fromJson(br, YourObject.class);
UPDATE
With respect to your comment, when you don't want or can't create a bean it usually boils down to parsing JSON to map. GSON (afaik) doesn't have a built-in for this, but its not hard to build a method that will traverse GSON's objects. You have an example in this blog
http://itsmyviewofthings.blogspot.it/2013/04/jsonconverter-code-that-converts-json.html
As you seem to be open to alternatives, take a look at Jackson as well (the two libs are the de-facto standard in JAVA).
With jackson you don't have to create a bean to support deserialization, e.g.
String json = "{\"id\":\"masterslave\"}";
Map<String,String> map = new HashMap<String,String>();
ObjectMapper mapper = new ObjectMapper();
//convert JSON string to Map
map = mapper.readValue(json,
new TypeReference<HashMap<String,String>>(){});
http://www.jsonschema2pojo.org/
That link helps generate the Java object format based on the GSON you feed in. Just make sure you set the settings exactly as you need it. As always, it's not a good idea to just copy-paste generated code, but it might be of help.

Using Gson how to add variable name as top level parameter for json of a REST call

I am trying call a REST service and using gson I am getting the following json for the following java pojo.
pojo
public class AlphaParameters {
private int one;
private int two;
private int three;
//getter setters
//constructors
}
Json
{"one":4,
"two":5,
"three":10
}
I am using the following code
Gson gson = new Gson()
AlphaParameters alphaParameters = new AlphaParameters(one,two,three);
gson.toJson(alphaParameters );
Earlier this code used to work, but now seems the server side which is on .net changed their implementation and now they are expecting the json in the following format. Everything is same but seems now they want the toplevel variable name in the json.
{"alphaParameters":
{"one":4,
"two":5,
"three":10
}
}
Question : Is there a specific api of Gson which I can use to generate the above json without refactoring my code ?
Or writing a wrapper class to include alphaParameters will be a better approach .
( I will have to write a lot of boilerplate code for latter ).
Thanks for your help.
I don't think Gson itself allows this kind of serialization but there is a number of ways you could tackle this problem without creating wrapper classes.
In my comment, I suggested putting the object in a map but that's a bit strange and you can do it so it looks more obvious in the code and probably performs better.
public Gson wrapJson(Object objectToSerialize) {
Gson gson = new Gson();
JsonObject result = new JsonObject();
//Obtain a serialized version of your object
JsonElement jsonElement = gson.toJsonTree(objectToSerialize);
result.add(objectToSerialize.getClass().getSimpleName(), jsonElement);
return result;
}
Then you can use it like this:
AlphaParameters alphaParameters = new AlphaParameters(one,two,three);
wrapJson(alphaParameters);
This allows you to use one pretty universal method in every case like this without writing boilerplate classes.
I used the class name to generate the key but feel free to modify this as it suits you. You could pass the key name as a parameter to make this wrapper utility more flexible.

Jackson \ GSON - Pojo to JSON and vice versa. is file \ serialization mandatory?

I'm in need of a JSON - > Pojo - > JSON transformation.
I looked into the mainstream libraries Jackson and GSON,
Apparently both use:
//write converted json data to a file named "file.json"
FileWriter writer = new FileWriter("c:\\file.json");
or In\Output Streams..
Two things scare me the most when i write new code:
I\O (HD specifically)
Serialization
I try to avoid both of these as much as I can.
Is there any alternative way to do this?
Those libraries DO NOT need to use files to operate, so answering your question: NO, file serialization is not mandatory. In fact it's not only not mandatory, but it'd be such a pain in the ass to read/write from/to a file each time you need to serialize/deserialize a JSON reponse!
In your example they use a File to write and read the JSON in order to imitate the usual scenario, which probably includes pass data from/to a web service for example, instead of from/to a File...
In fact, for example in Gson, serialization/deserialization is quite straightforward with a simple Pojo, just like this:
Serialization
Pojo pojo = new Pojo();
Gson gson = new Gson();
String pojoJSON = gson.toJson(pojo);
Deserialization
Gson gson = new Gson();
Pojo pojo = gson.fromJson(pojoJSON, Pojo.class);
I suggest you to take a look at Gson documentation, which is pretty clear and quite short, once you read it you'll understand everything much better...

How to marshall POJO to JSON using JETTISON?

I have done the marshalling of a JaxB java object to Json using JETTISON. But I can not marshall a simple java object (which has no annotations in it) to Json using JETTISON. I know it is possible to do it by using GSON or MOXy or some other providers.
But I like to get clear "Can we do it using JETTISON?"., If we can, How to do it?
Thanks in Advance.
Don't waste your time, this is simply not what Jettison was designed to do. Conceivably, it would have been possible to instantiate a JSONObject with your POJO and serialize it that way, but there are some issues with its code that make this next to impossible:
It requires passing in the names of the fields that will be included in the JSON.
It can only process public properties of the supplied object.
Not to mention it cannot handle nesting of any kind. Take a look at this lovely code:
Class c = object.getClass();
for (int i = 0; i < names.length; i += 1) {
try {
String name = names[i];
Field field = c.getField(name);
Object value = field.get(object);
this.put(name, value);
} catch (Exception e) {
/* forget about it */
}
}
Yep, thats the code in the constructor JSONObject(Object, String[]). I'm sure you will see the problems with it (raw access to generic objects, can only access public fields, sloppy exception handling). All in all - very bad 'serialization' code.
I know its probably not what you want to hear, but if you want to convert regular Java objects to JSON then you might want to stick with one of the more general-purpose libraries.
JAXB (JSR-222) is configuration by exception and only requires annotations where you need to override the default XML representation (Jettison converts XML StAX events to/from JSON). Instead of #XmlRootElement you can wrap your object in an instance of JAXBElement.
http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html

Serialize an object to json in Java?

I am trying to serialize an instance of Campaign in Adwords API with gson at first with the code below:
Campaign c = new Campaign();
c.setName("beijing");
c.setId(23423L);
Gson gson = new Gson();
String json = gson.toJson(c);
and I get the exception that class Money declares multiple JSON fields named __equalsCalc. When I try to serialize the instance with json plugin of struts2 with the code below
String str = org.apache.struts2.json.JSONUtil.serialize(c);
System.out.println(str);
It works and output the correct result
{"adServingOptimizationStatus":null,"biddingStrategy":null,"budget":null,"campaignStats":null,"conversionOptimizerEligibility":null,"endDate":null,"frequencyCap":null,"id":23423,"name":"beijing","networkSetting":null,"servingStatus":null,"settings":null,"startDate":null,"status":null}
Then my question is that why can the json plugin of struts2 can serialize the instance correctly while gson cannot? Can I use the json plugin of struts2 to serialize objects to json since it is design to produce json result in struts2 not for this situation.
You can use the json plugin in struts2 to serialize your object manually to json string. You can do that by calling the serialize static method.
String jsonString = JSONUtil.serialize(your_object);
Don't forget to include xwork-core jar in your classpath because it depends on it.
Sounds like either a bug in Gson or it is more particular/less robust. Without looking at the code for either it would be hard to know more.
Personally I use Jackson for JSON to POJO transformations.
Ultimately as long as the Structs2 plugin is available on your classpath I don't see why you couldn't leverage it's classes to handle JSON transformations. Ultimately JSON is a format therefore all JSON libraries need to produce commonly understandable data.
I had a similar problem and solved it by moving my use of SimpleDateFormat from the class level to inside a method. GSON doesn't have to serialize SimpleDateFormat this way.
Hope this helps someone - 45 minutes of head banging for me! :-)

Categories