How to decode a json string with gson in java? - java

I have a json string (the stream of social network Qaiku). How can I decode it in Java?
I've searched but any results work for me.
Thank you.

Standard way of object de-serialization is the following:
Gson gson = new Gson();
MyType obj = gson.fromJson(json, MyType.class);
For primitives corresponding class should be used instead of MyType.
You can find more details in Gson user's guide. If this way does not work for you - probably there's some error in JSON input.

As an example using Gson, you could do the following
Gson gson = new Gson();
gson.fromJson(value, type);
where value is your encoded value. The trick comes with the second parameter - the type. You need to know what your decoding and what Java type that JSON will end in.
The following example shows decoding a JSON string into a list of domain objects called Table:
http://javastorage.wordpress.com/2011/03/31/how-to-decode-json-with-google-gson-library/
In order to do that the type needs to be specified as:
Type type = new TypeToken<List<Table>>(){}.getType();
Gson is available here:
http://code.google.com/p/google-gson/

Related

Use GSON to parse json objects into java.util.HashMap

I am trying to parse a json object with this format:
{
'result': (json array or json object) ,
}
The code I am using to parse the json string is:
Map<String, Object> responseMap = new Gson().fromJson(
json,
new TypeToken<HashMap<String, Object>>() {}.getType()
);
When the result field is a JSON object checking with the following line of code returns "LinkedTreeMap"
// returns "LinkedTreeMap"
responseMap.get("result").getClass().getSimpleName()
Likewise, all nested JSON objects are parsed into com.google.gson.internal.LinkedTreeMap. Is there a way to make GSON parse JSON objects into java.util.HashMap by default instead of com.google.gson.internal.LinkedTreeMap.
The usual way to solve this problem seems to be to write a class that defines the structure I'd expect to see in the response JSON object. However, the value contained in the 'result' field can be a JSON object or a JSON array, and I do not have a standard format for the expected return objects and what they may contain.

How do I convert a LinkedTreeMap to gson JsonObject

For a java data handler, I send properly formatted JSON, but a combination of Spring, Java deciding how to cast what it sees, and frameworks I really shouldn't go changing mangle that JSON so that once I can see it, it's turned into a LinkedTreeMap, and I need to transform it into a JsonObject.
This is not to serialize/de-serialize JSON into java objects, it's "final form" is a gson JsonObject, and it needs to be able to handle literally any valid JSON.
{
"key":"value",
"object": {
"array":[
"value1",
"please work"
]
}
}
is the sample I've been using, once I see it, it's a LinkedTreeMap that .toString() s to
{key=value, object={array=[value1, please work]}}
where you can replace "=" with ":", but that doesn't have the internal quotes for the
new JsonParser().parse(gson.toJson(STRING)).getAsJsonObject()
strategy.
Is there a more direct way to convert LinkedTreeMap to JsonObject, or a library to add the internal quotes to the string, or even a way to turn a sting into a JsonObject that doesn't need the internal quotes?
You'd typically have to serialize the object to JSON, then parse that JSON back into a JsonObject. Fortunately, Gson provides a toJsonTree method that kind of skips the parsing.
LinkedTreeMap<?,?> yourMap = ...;
JsonObject jsonObject = gson.toJsonTree(yourMap).getAsJsonObject();
Note that, if you can, just deserialize the JSON directly to a JsonObject with
gson.fromJson(theJson, JsonObject.class);

How to access nested elements from a JSON using Java (Bing-Search-API)

I have this JSON that I retrieved using Bing-Search-API. Now, I'm not sure how to access the nested elements using GSON. I already made the source files for the JSON Structure Data.
If I do this:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(jsonText).getAsJsonArray();
It is going to throw me that is not a JsonArray, so If I change it to JsonObject, how can I retrieve the String MediaUrl from Results.java?
Thank you
Based on the javadoc of Gson class:
Gson gson = new Gson();
Response response = gson.fromJson(jsonText, Response.class);
Results firstResult = response.getD().getResults().get(0);
System.out.println(firstResult.getMediaUrl());
So you don't need to use the JsonParser directly.
Your java classes have to be modified a little bit for this to work:
the type of results field in D.java has to be List<Results> so that Gson can find out the class of objects to populate with.
the naming of attributes/fields is inconsistent, some starts with lower case, others with uppercase. Make sure they are the same in the java classes and in the json string (considering case sensitivity). This issue might be addressed with using the appropriate FieldNamingStrategy for serialization/deserialization.

Java - JSONObject charset

I'm using JSONObject from org.json.*
I need to construct JSONObject with string fields like this
field:"englishletters123\u1234\u3456"//UTF-8 encoding
so, I'm doing this
myJSONObject.put("field", myString);
But instead of this I'm getting object with fluent (non-english) letters instead of their UTF-8 representation.
String newString = new String(oldString.getBytes(...), ...);
myJSONObject.put("field", newString);
doesn't work as well
Is there any way to make such operation? Maybe I should use some other library?
I'm not overly familiar with that JSON serialization library, but since you asked, the GSON library from google is amazing. It handles nearly everything through reflection, it's as simple as creating an object that fit the description of the JSON text you are attempting to create.
for example:
public class Thing{
public String field = "whatever you want";
}
Gson gson = new Gson();
String jsonString = gson.toJson(new Thing());
de-serializing is simple too:
Thing t = gson.fromJson(jsonString, Thing.class);
Of course, there's much more to the library, but that's the basics of it.

Java object from JSON input file

Hi I have a json input file as follows,
{'Latitude':'20',
'coolness':2.0,
'altitude':39000,
'pilot':{'firstName':'Buzz',
'lastName':'Aldrin'},
'mission':'apollo 11'}
How to create a java object from the json input file.
Thanks
You can use the very simple GSON library, with the Gson#fromJson() method.
Here's an example: Converting JSON to Java
There are more than one APIs that can be used. The simplest one is JSONObject
Just do the following:
JSONObject o = new JSONObject(jsonString);
int alt = o.getInt("altitude");
....
there are getXXX methods for each type. It basically stores the object as a map. This is a slow API.
You may use Google's Gson, which is an elegant and better library -- slightly more work required than JSONObject. If you are really concerned about speed, use Jackson.

Categories

Resources