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! :-)
Related
a:34:
{
s:2:\"id\";
i:14;
s:10:\"created_at\";
s:19:\"2017-02-20 17:09:01\";
s:10:\"updated_at\";
s:19:\"2017-11-01 08:30:43\";
s:11:\"id\";i:3;s:7:\"username\";
}
these is format i am getting, how to deserialize.
Any help thankyou
The google has a very good library for JSON serialization/deserialization, named
Gson.
If you have a json string and you want to deserialize, you can do it simply by calling:
new Gson().fromJson(yourJsonString, Model.class);
where Model is the model class, where you can map your json string. If you check the library documentation, you can find more interesting things.
I have this simple code:
package com.example
import javax.json.Json;
import javax.json.JsonObject;
...
#Path("/")
public class Resource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response defaultEntry() {
JsonObject result = (Json.createObjectBuilder()
.add("hello", "world")
.build());
return Response.status(200).entity(result.toString()).build();
}
}
I am new to Java, could someone please explain why, if I omit the call to result.toString() and simply pass result to .entity (like so: return Response.status(200).entity(result).build()), I get JSON on the client that includes type information etc, but not what I expected:
{"hello":{"chars":"world","string":"world","valueType":"STRING"}}
what is the intention of this? How is passing JsonObject to it different from passing a string?
Also, I did not find Response.entity method in the documentation (https://jersey.java.net/apidocs/2.11/jersey/javax/ws/rs/core/Response.html). I copied this code from a tutorial, that did not explain properly what is going on...
I wish I had a better answer for you, this more of a hint until a better answer arrives. There are a few moving parts here. JsonObject is an interface. Its implementation is not described. Furthermore there is a Json serializer that is turning your returned objects into Json text. It is both these things together that is leading to this Json schema output. When you did the .toString() variation, the serializer just returned the String as is. But when you return the JsonObject now you have these two dynamics at play, the implementation of the JsonObject and the implementation of the serializer. Since you are using Jersey 2.0 you could be using Jackson, Moxy, or Jettison serializers. These all might have different output when serializing the JsonObject, but we would have to test to be sure. Furthermore, the JsonObject implementation might be configured in a way that when serialized by your chosen serializer leads to its output being a Json schema, versus just regular Json. This can be done using annotations that are specific to the chosen Json serializer.
In my career I have used multiple Json serializers. Jackson is probably the most popular one out there. But I have also used Gson extensively. In one project we configured Gson in some way where its serialized Json output came out as a Json schema when serializing POJO's. So its not far fetched to have a Json serializer output Json schema under certain conditions.
When serializing POJO's (aka Java Beans), you expect a regular Json output when using default settings of your serializer on a Java Bean. But when sending back objects that could have complex interworkings with specific Json serializers you may get varying Json output.
In this situation you would have to run tests to dive deeper into what is going on. For example, I would first test out the serializer against a POJO that matches the JsonObject you created. Then I would also test out other Json serializers on the same JsonObject. See if you can pick up on a pattern.
The datatype module jackson-datatype-jsr353 provides support for javax.json types. The page includes instructions how to add the dependency and register the module with Jackson's ObjectMapper.
Starting with Jackson 2.11.0, the module moved under the umbrella of jackson-datatypes-misc.
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.
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...
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.