Parse json string to object using Gson - java

I tried converting my json string to java object by using Gson but somehow it was not successful and I haven't figured out why..
My Json string
{
"JS":{
"JS0":{
"Name":"ABC",
"ID":"5"
},
"JS1":{
"Location":"UK",
"Town":"LD"
},
"JS2":{
"Usable":"true",
"Port":"ABC"
}
}
}
In java code I have 4 classes, JS, JS0, JS1 and JS2
JS class contains JS0, JS1 and JS2 variables
JS0, JS1 and JS2 classes contain fields as in Json string example, e.g. JS0 contains 02 fields, String Name and String ID
In all classes I have getter/setter for variables, 02 constructors (01 with empty parameters and another one with all variables in the parameter field)
And for using Gson:
Gson gson = new Gson();
jsObject = gson.fromJson(sb.toString(), JS.class);
When I access JS0, JS1 and JS2 objects from jsObject, they are null...
Can someone show me what did I do wrong?
Thank you very much,

The problem here is, you are trying to convert
{
"JS" : {
/* rest of JSON */
}
}
to JS object, but the above JSON is a representation of Java class like this
class Foo {
JS JS;
}
So, you need to get the value of JS from the JSON string first, then call fromJSON to deserialize it with the JS.class passed as the second parameter.
OR
Create a simple class containing only JS as a variable, then call fromJSON with that class passed as the second parameter of fromJSON like this:
Java
class Foo {
JS JS;
}
jsObject = gson.fromJson(sb.toString(), Foo.class);

Related

How to check json for key and if it exists then set the value in java model Object

I have a model object which is initialized with default values. To refresh the content of object I call an web service and get the response and get the content from json object.
I want to check If json response contains the object or not. If it does then call the setter and set the data and if it doesn't then leave then don't set it. I have approx 300 fields in my object. How I can do it with less code. I am listing my current approach.
My Model object is like
public class MyObject {
private String str1 = "Initial Value1";
private String str2 = "Initial Value2";
public void setStr1(String str1)
{
this.str1 = str1;
}
public void setStr2(String str2)
{
this.str2 = str2;
}
public String getStr1(){
return str1;
}
public String getStr2(){
return str2;
}
}
my json response be like
{
"val_one":"New Value1",
"val_two":"New_value2"
}
Now at run time I need to set the value from json response
MyObject myObject = new MyObject();
if(jsonObject.has("val_one"));
myObject.setStr1(jsonObject.get("val_one"));
if(jsonObject.has("val_two"));
myObject.setStr2(jsonObject.get("val_two"));
Now how to do it in a better and efficient
If both sides are using JAVA then why not just use json-io. You can create an object as normal. ie
Animal a = new Aminmal() andimal.setName("bob");
Then use json-io to make it into json -- stream to where ever it needs to be... use json io to change back to object
This can be done using
JsonWriter.objectToJson(Object o);
JsonReader.jsonToJava(String json);
https://code.google.com/p/json-io/
json-io is also extremely light weight and quicker than most if not all other third party json library's that I have used.
That being said if you want to have more control on the output ie.. date conversions etc.. then look at GSON.
https://code.google.com/p/google-gson/
Another option, in addition to the other suggestions is gson. Here the link for gson information.
Essentially the idea with gson being that you define an object to represent the JSON structure that you are receiving. So somewhat like what you have now, you'd just need to change the object attributes to match the names of the JSON fields, ie 'val_one' and 'val_two'.
Then you just need to use gson to create the object from the JSON text, eg:
Gson gson = new GsonBuilder().create();
MyObject json = gson.fromJson(jsonStr, MyObject.class);
Why do you want to take of the object model mapping yourself? If you take spring then you can use the jackson mapper and have it all done for you.
If you don't want to use spring then you still can use jackson2 and let it handle the parsing:
http://wiki.fasterxml.com/JacksonRelease20

Map generic JSON object to Map interface with GSON

Given the following JSON object
{
"id": 5,
"data: { ... }
}
Is it possible to map this to the following POJO?
class MyEntity {
int id;
Map<String, Object> data;
}
Because I would like to leave the data object open ended. Is this even possible or what is a better approach to go about this? I am doing this on Android.
I don't have any idea about Android application but you can achieve it using Gson library easily.
The JSON that is used in your post is not valid. It might be a typo. Please validate it here on JSONLint - The JSON Validator
Simply use Gson#fromJson(String, Class) method to convert a JSON string into the object of passed class type.
Remember the name of instance member must be exactly same (case-sensitive) as defined in JSON string as well. Read more about JSON Field Naming
Use GsonBuilder#setPrettyPrinting() that configures Gson to output Json that fits in a page for pretty printing.
Sample code:
String json = "{\"id\": 5,\"data\": {}}";
MyEntity myEntity = new Gson().fromJson(json, MyEntity.class);
String prettyJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(myEntity);
System.out.println(prettyJsonString);
output:
{
"id": 5,
"data": {}
}

How can i get information from JSON dictionary in java

I have a dictionary on a website in form of json which looks for example like this:
"types":[{
"id":"0",
"name":"value1"
},{
"id":"1",
"name":"value2"
},{
"id":"2",
"name":"value3"
}]
I cant find any useful example of a method that could help me retrieve that information and put it in, for example, a string array.
Maybe anyone of you come across same problem please help!
P.S. I tried method like simplest way to read json from a URL in java with no success.
It is array of json object value whose key is types. You can use json-java library like gson, jackson,flexjson etc.. to parse this json object and achieve your required result.
GSON Example -
JsonElement jElement = new JsonParser().parse(jsonString);
JsonObject jObject = jElement.getAsJsonObject();
jObject = jObject.getAsJsonObject("types");
Or you can use pojo class like -
public class Type {
private int id;
private String name;
...
}
gson.fromJson(jsonString, Type.class);
Refer java docs.

Java add function to json object without using quotes.

I'm building a json object in java. I need to pass a function into my javascript and have it validated with jquery $.isFunction(). The problem I'm encountering is I have to set the function in the json object as a string, but the json object is passing the surrounding quotes along with object resulting in an invalid function. How do I do this without having the quotes appear in the script.
Example Java
JSONObject json = new JSONObject();
json.put("onAdd", "function () {alert(\"Deleted\");}");
Jquery Script
//onAdd output is "function () {alert(\"Deleted\");}"
//needs to be //Output is function () {alert(\"Deleted\");}
//in order for it to be a valid function.
if($.isFunction(onAdd)) {
callback.call(hidden_input,item);
}
Any thoughts?
You can implement the JSONString interface.
import org.json.JSONString;
public class JSONFunction implements JSONString {
private String string;
public JSONFunction(String string) {
this.string = string;
}
#Override
public String toJSONString() {
return string;
}
}
Then, using your example:
JSONObject json = new JSONObject();
json.put("onAdd", new JSONFunction("function () {alert(\"Deleted\");}"));
The output will be:
{"onAdd":function () {alert("Deleted");}}
As previously mentioned, it's invalid JSON, but perhaps works for your need.
You can't. The JSON format doesn't include a function data type. You have to serialise functions to strings if you want to pass them about via JSON.
Running
onAdd = eval(onAdd);
should turn your string into a function, but it's buggy in some browsers.
The workaround in IE is to use
onAdd = eval("[" + onAdd + "]")[0];
See Are eval() and new Function() the same thing?

How to get JSON data from an url in Java?

I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?:
[
{
"user":{"id":"1","username":"user1"},
"item_name":"item1",
"custom_field":"custom1"
},
{
"user":{"id":"2","username":"user2"},
"item_name":"item2",
"custom_field":"custom2"
},
{
"user":{"id":"3","username":"user3"},
"item_name":"item3",
"custom_field":"custom3"
}
]
If you want to use Gson, then first you declare classes for holding each element and sub elements:
public class MyUser {
public String id;
public String username;
}
public class MyElement {
public MyUser user;
public String item_name;
public String custom_field;
}
Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it:
MyElement[] data = gson.fromJson (myJSONString, MyElement[].class);
Then you simply access the elements of data.
The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. e.g. "id", "item_name" etc.
If your trying to serialize/deserialize json in Java I would recommend using Jackson. http://jackson.codehaus.org/
Once you have Jackson downloaded you can deserialize the json strings to an object which matches the objects in JSON.
Jackson provides annotations that can be attached to your class which make deserialization pretty simple.
You could try JSON Simple
http://code.google.com/p/json-simple/
Example:
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonDataString);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject obj = (JSONObject) jsonArray.get(i);
//Access data with obj.get("item_name")
}
Just be careful to check for nulls/be careful with casting and such.

Categories

Resources