Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to parse some JSON data to Java using GSON but I am unable to do so due to the way it is formatted. I've looked around a lot but none of the information I found helped me work this out. I haven't had much experience with JSON, especially when parsing it to Java. I would appreciate any help I get for this.
JSON URL:
http://xpaw.ru/mcstatus/status.json
EDIT:
I took your advise about using Jackson and went through some guides and tried making it, Heres my code:
Main Class: http://pastebin.com/XRcpkAuP
UptimeCheck Class: pastebin/f2UanvhY (Sorry, I couldnt post more than 2 links :/)
For some reason, It doesnt seem to be able to parse the link. Could someone please help me out?
Thank You
I personally recommend to use Jackson to convert JSON to/from Java. Jackson is a High-performance JSON processor Java library.
Below snippets would give a basic idea to this library.
//1. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\report_data.json"), ReportData.class);
//2. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\report_data.json"), reportData);
Both writeValue() and readValue() has many overloaded methods to support different type of InputStream and OutputStream.
Example for your reference: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Shishir
I dont know about gson, but your JSON String is valid. You can use the following:
This is simple code to do it, I avoided all checks but this is the main idea.
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").toString();
return result;
}
To make the use more generic - you will find that the [javadoc][1] of this are pretty clear and helpful.
I read it in another article.. Using GSON seems to be good....
Simplest thing usually is to create matching Object hierarchy, like so:
This is an example
public class Wrapper {
public Data data;
}
static class Data {
public Translation[] translations;
}
static class Translation {
public String translatedText;
}
and then bind using GSON, traverse object hierarchy via fields. Adding getters and setters is pointless for basic data containers.
So something like:
Wrapper value = GSON.fromJSON(jsonString, Wrapper.class);
String text = value.data.translations[0].translatedText;
Related
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.
This is related to deserializing a JSON object with multiple items inside it .
I have the following Json object I need to deserialize in Java using Gson, and for the life of me, I'm pulling my hair out.
{
"Success":1,
"return":
{"MyObjects":
{"Obj1":
{"Prop1":"widgets", "Label":"Obj1", "prop2":"gadgets"}}
{"Obj2":
{"Prop1":"widgets2", "Label":"Obj2","prop2":"gadgets2"}}
{"Obj3":
{"Prop1":"widgets3", "Label":"Obj3","prop2":"gadgets3"}}
}
I have read and re-read the above linked question, and I am not quite understanding his solution.
I can make a MyJsonObject class as follows:
public class MyJasonObject{
private int success;
#SerializedName("return")
private isReturn isreturn;
}
The 'isReturn' class is where I'm lost. How should I parse the "MyObjects" into a map or a Json object? I didn't write the json string, it was handed to me... It looks like I could use a map for Myobject using the label field. But, I honestly don't know how to.
I've read a bunch of different articles, comparations and tutorials that are using different JSON-Libraries for parsing (and creating) JSON into Java Objects. Anyway I think that I've got the facts right cause I've decided to use the JSON library called Jackson.
GSON is simple and robust but way to slow acording to me. So I decided to actually try this Jackson thing out but, it seems like the parsing is a little bit more confusing here than with GSON.
The data-type of the value that I want to parse is simply an Boolean.
This is what the JSON that I'm trying to parse looks like:
{"FooResult":true}
So what I actually need help with is selecting the value from the key FooResult and then parse its value into an Boolean.
This Is what I've done so far:
String json = getString(request);
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, Boolean.class);
But this code obviously gives me an error cause I haven't selected that it is the FooResult key that I'm interested in reading & parsing into an Boolean.
You should create a new class like this:
class MyClass {
public boolean FooResult;
}
And use this code to load the data:
MyClass myObject = mapper.readValue(json, MyClass.class);
Then you can access the value with myObject.FooResult
Ok this is lame. Even lamer when I rethink about it. The problem the whole time have been that the class of the object that you want to parse needs to be static. I've tried what Simon suggested like four or five times before I even posted this question today but the problem all time was that the class wasn't static.
So now it finally works.
static class FooClass
{
public boolean FooResult;
}
And for the parsing process.
String json = getString(request);
ObjectMapper mapper = new ObjectMapper();
FooClass fooClass = null;
try
{
fooClass = mapper.readValue(json, FooClass.class);
}
boolean result = fooClass.FooResult;
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.