Convert Json to a java object - java

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.

Related

Jackson reading all numbers as BigDecimal

We are using Jackson to read json from the filesystem and parse it to the POJO.
POJO
String name;
Map<String,Object> map;
getters/setters
Reading
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
Pojo obj = mapper.readValue(jsonFile, Pojo.class);
Problem
When we have numbers in json (map part) they gets converted to Integer Or Double.And we want all our numbers (decimal and whole) as Type BigDecimal So I tried using the
mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
But this only works for the decimal numbers. There is no feature available to covert whole numbers to BigDecimal.
Question
Do we have any inbuilt feature to enable ObjectMapper to read all the number to BigDecimal?
If I need to write custom serializer, Do I need to write it for the whole class or it can be written for Map field ?
You can register a Module with your ObjectMapper that includes a custom JsonDeserializer. You don't need to make your own because Jackson Databind provides a BigDecimalDeserializer but you need to do one more thing to make it work.
Because BigDecimalDeserializer is annotated with #JacksonStdImpl, Jackson won't allow you to use this directly because the initialization code (I currently disagree with this) specifically checks for this annotation and disallows it. Because this deserializer is not a final, you can get around this without copy-pasting by creating an anonymous subclass.
In the end, it will look something like this
Module module = new SimpleModule();
module.addDeserializer(Number.class, new NumberDeserializers.BigDecimalDeserializer() {});
new ObjectMapper().registerModule(module).readValue("{}", Map.class);
Try putting :BigDecimal:[dps] is in your json. For example :
{
"MY_BIG_D:BigDecimal:0" : 3
}
where dps = decimal places.

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...

HashMap to JsonSting?

I am working on a GWT application.
I want to convert a hashMap to JSON String and send it to GWT server
My HashMap is like HashMap<String, CustomProperties)
CustomProperties is the class with different parameters. This HashMap is property of file .
I want to uplaod a file with these properties.
What I am going to do : Attach the json Sting to hidden field and send it with the file through the formPanel.
But I dont know how to do Hashmap to JSON String.
Can anyone guide me in this regard ?
Consider using the GWT AutoBean framework for serializing to and from JSON.
JohnS' answer makes sense.
However, there is a related and a long ago answered question: GWT HashMap to/from JSON for details.
You could give Jackson a try.
http://wiki.fasterxml.com/JacksonInFiveMinutes
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(outputStream, yourMap);
yourMapinJson=outputStream.toString();

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! :-)

JSON to Objects in 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.

Categories