private FbDataToServer generateFbDataToServer(
GraphObject graphObject) {
Gson gson = new Gson();
FbDataToServer fbDataToServer = new FbDataToServer();
ֿ fbDataToServer.fbJson = gson.toJson(graphObject
.getInnerJSONObject());
Everytime I try to parse FB graphObject object to Json -
an error is thrown.
How can it be? how can an object be not json serializable?
The error said the object is not serializable.
I'll try to get reproduce the error again.
Actually, i have never use the facebook API. But when it comes to serialize the object to json string, i recommend you that fastjson is much better.
https://github.com/alibaba/fastjson
Fastjson is the fastest processing library in java (even than jackson, let alone gson) and it has no special requirements to the object ,just be the pain java bean is enough.
By the way, fastjson is developed by Chinese, so its documentation are mainly in Chinese. If you have trouble with its api, you can contact with 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.
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...
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! :-)
I would like to know how to parse a JSON feed by items (eg. url / title / description for each item). I have had a look to the doc / api but, it didn't help me.
This is what I got so far
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class ImportSources extends Job {
public void doJob() throws IOException {
String json = stringOfUrl("http://feed.test/all.json");
JsonObject jobj = new Gson().fromJson(json, JsonObject.class);
Logger.info(jobj.get("responseData").toString());
}
public static String stringOfUrl(String addr) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
URL url = new URL(addr);
IOUtils.copy(url.openStream(), output);
return output.toString();
}
}
Depends on the actual JSON format. You can in fact just create a custom Javabean class which matches the JSON format. Any fields in JSON can be mapped as String, Integer, Boolean, etc Javabean properties. Any arrays can be mapped as List properties. Any objects can be mapped as another nested Javabean property. It greatly eases further processing in Java.
Without a JSON string example from your side, it's only guessing how it would look like, so I can't give a basic example here. But I've posted similar answers before here, you may find it useful:
Converting JSON to Java
Generate Java class from JSON?
Gson has also an User Guide, you may find it useful as well.
Gson 1.4 has a new API JsonStreamParser that lets you parse multiple JSON objects one by one from a stream.
You can create corresponding java classes for the json objects. The integer, string values can be mapped as is. Json can be parsed like this-
Gson gson = new GsonBuilder().create();
Response r = gson.fromJson(jsonString, Response.class);
Here is an example- http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html
I don't know if GSON can do streaming/incremental binding (I thought it did not).
But is there specific reason to only consider that particular library? Other Java JSON processing libraries do allow such processing (you can check links the other answer has for some ideas), since it is quite important feature when processing large feeds.