I am in trouble. I can not deserialize this object that I return json from an http request. Can anyone help me?
I downloaded and added to the libs folder gson_2.2.4.jar.
We insert the object json
{
"returnCode": 0,
"data": [
{
"token": "aaaaa =",
"code": "xx",
"id": ""
}
],
"errorMsg": ""
}
You need to create a class of data object, for example
public class DataObj {
public String token;
public String code;
public String id;
}
and then create another class for the whole json, for example
public class MyObj {
public int returnCode;
public DataObj[] data;
public String errorMsg;
}
then create an object of MyObj and use deserializer from GSON to read json,
for example:
GSON gson = new GSON();
MyObj newMyObj = gson.fromJson(jsonString, MyObj.class);
Where jsonString contains the json object as string.
(#Shivam Verma thanks for your edit)
Related
In our project is, the models are generated,
what I need to do is change
{
"name": "someName",
"model" :" modelID"
}
to
{
"car":
{
"name": "someName",
"model" :" modelID"
}
}
from my class
public class Car {
private String name;
private String model;
... getter and setters ...
}
Is there some kind of configuration or ... to do this ? I know it is possible with jackson, but we are using Gson
thx
found 2 ways to do this
using GsonFireBuilder
Gson gson = new GsonFireBuilder().wrap(Car.class,"Car").createGson();
Gson gson = new Gson();
JsonElement je = gson.toJsonTree(new Car());
JsonObject jo = new JsonObject();
jo.add("Car", je);
I am trying to map below JSON to a POJO Class using Gson library. Below is the JSON response and POJO Class and mapping done
import java.util.Map;
import com.google.gson.JsonElement;
public class DataResponse {
private String $status;
private Map<String, JsonElement> $payload;
public String get$status() {
return $status;
}
public void set$status(String $status) {
this.$status = $status;
}
public Map<String, JsonElement> get$payload() {
return $payload;
}
public void set$payload(Map<String, JsonElement> $payload) {
this.$payload = $payload;
}
}
Here is the Sample JSON.
{
"$status": "OK",
"$payload": {
"$nextStart": "123",
"$results": [
{
"$key": "101",
"score": 3,
"to": "Test1"
},
{
"$key": "102",
"score": 4,
"to": "Test2"
},
]
}
}
Below is the mapping done. Is there some problem with POJO class definition. Since I cannot get all the elements of JSON response mapped to the innermost element from the response. Appreciate your support in providing useful suggestions.
Gson gson = new Gson();
DataResponse dataResponse = gson.fromJson(EntityUtils.toString(response.getEntity()),
DataResponse.class);
While working with marshalling and unmarshalling, it is always good to have a model defined as:
public class DataResponse {
private String $status;
private Payload $payload;
// getters and setters
}
class Payload {
private String $nextStart;
private List<Result> $results;
// getters and setters
}
class Result {
private String $key;
private String score;
private String to;
// getters and setters
}
Now when you convert json to POJO as:
Gson gson = new Gson();
DataResponse dataResponse = gson.fromJson(EntityUtils.toString(response.getEntity()), DataResponse.class);
it can easily convert it.
Also, believe me, it is good for processing in your further code!
Update: if you really want to convert json to Map, then you can do something like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson("{'key':'value'}", type);
Substitute json string there.
I am trying to parse a JSON response documents using Gson but after parse it's giving me a null value
My JSON response is a Array of Documents
Java Code
//Code to convert the response into JSON
String res = gson.toJson(results);
//Parse the JSON
java.lang.reflect.Type collectionType = new TypeToken<List<Objects.JsonResponse>>() {}.getType();
List<Objects.JsonResponse> resp = gson.fromJson(res, collectionType);
System.out.println(resp.get(2).getName());
JAVA Object
package Objects;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class JsonResponse {
#SerializedName("product_id")
public static String product_id; //17
#SerializedName("create_date")
public static String create_date; //45
#SerializedName("image_small")
public static String image_small; //85
#SerializedName("image_large")
public static String image_large; //133
#SerializedName("name")
private static String name; //174
#SerializedName("description")
public static String description; //266
#SerializedName("tagline")
public static List<String> tagline;
#SerializedName("category")
public static List<String> category;
#SerializedName("catlevel0")
public static List<String> catlevel0;
#SerializedName("catlevel1")
public static List<String> catlevel1;
#SerializedName("catlevel2")
public static List<String> catlevel2;
#SerializedName("color")
public static List<String> color;
#SerializedName("size")
public static List<String> size;
#SerializedName("_version_")
public static String _version_;
#SerializedName("product_id")
public static String getName() {
return name;
}
public static void setName(String name) {
JsonResponse.name = name;
}
}
JSON document to be parsed is:
[
{
"product_id": "prod3400008",
"create_date": "2011-02-17T00:00:00Z",
"image_small": "/hul_images/small/17_Rexona.jpg",
"image_large": "/hul_images/large/17_Rexona.jpg",
"name": "Small Shell Cluster Loop Earrings",
"description": "Small Shell Cluster Loop Earrings",
"tagline": [
"B1G1 75% Off Jewelry "
],
"category": [
"Earrings"
],
"catlevel0": [
"Accessories"
],
"catlevel1": [
"Jewelry"
],
"catlevel2": [
"Earrings"
],
"color": [
"Clearly Coral",
"Mocha Brown",
"Blue Lagoon",
"Hunter Green",
"Medium Purple"
],
"_version_": 1527034576315089000
}
]
This is not a solutions, more like a tip. I found out the problem in your question. The problem is with the json array. If you remove all the arrays and just an object, this problem wont come. I dont know if you are aware of that already.
Please try the following json
{
"product_id": "prod3400008",
"create_date": "2011-02-17T00:00:00Z",
"image_small": "/hul_images/small/17_Rexona.jpg",
"image_large": "/hul_images/large/17_Rexona.jpg",
"name": "Small Shell Cluster Loop Earrings",
"description": "Small Shell Cluster Loop Earrings",
"_version_": 1527034576315089000
}
I removed all the arrays.
I have also removed the static declaration of your class JsonResponse, and static declaration of all your member variables.
And this is try this code:
Gson gson = new Gson();
String res = gson.toJson(results);
JsonResponse response = gson.fromJson(results, JsonResponse.class);
System.out.println(response.product_id);
System.out.println(response.create_date);
Hope this will help to figure out the problem. If you still cant find out, let me know... I will try harder... :-)
Object attributes are static and you should tell the GsonBuilder to serialize it.
follow this stack for more information.
Better practice would be not to make pojo class filed as static :)
Maybe it's giving you null because you messed up your annotations...
Also, remove static from all the methods and fields, you are trying to make instance variables, not class variables.
#SerializedName("product_id") // <---- not right
public String getName() { // <--- removed "static"
return name;
}
I trying to deserialize this json to array of objects:
[{
"name": "item 1",
"tags": ["tag1"]
},
{
"name": "item 2",
"tags": ["tag1","tag2"]
},
{
"name": "item 3",
"tags": []
},
{
"name": "item 4",
"tags": ""
}]
My java class looks like this:
public class MyObject
{
#Expose
private String name;
#Expose
private List<String> tags = new ArrayList<String>();
}
The problem is json's tags property which can be just empty string or array. Right now gson gives me error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING
How should I deserialize this json?
I do not have any control to this json, it comes from 3rd pary api.
I do not have any control to this json, it comes from 3rd pary api.
If you don't have the control over the data, your best solution is to create a custom deserializer in my opinion:
class MyObjectDeserializer implements JsonDeserializer<MyObject> {
#Override
public MyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jObj = json.getAsJsonObject();
JsonElement jElement = jObj.get("tags");
List<String> tags = Collections.emptyList();
if(jElement.isJsonArray()) {
tags = context.deserialize(jElement.getAsJsonArray(), new TypeToken<List<String>>(){}.getType());
}
//assuming there is an appropriate constructor
return new MyObject(jObj.getAsJsonPrimitive("name").getAsString(), tags);
}
}
What it does it that it checks whether "tags" is a JsonArray or not. If it's the case, it deserializes it as usual, otherwise you don't touch it and just create your object with an empty list.
Once you've written that, you need to register it within the JSON parser:
Gson gson = new GsonBuilder().registerTypeAdapter(MyObject.class, new MyObjectDeserializer()).create();
//here json is a String that contains your input
List<MyObject> myObjects = gson.fromJson(json, new TypeToken<List<MyObject>>(){}.getType());
Running it, I get as output:
MyObject{name='item 1', tags=[tag1]}
MyObject{name='item 2', tags=[tag1, tag2]}
MyObject{name='item 3', tags=[]}
MyObject{name='item 4', tags=[]}
Before converting the json into object replace the string "tags": "" with "tags": []
Use GSON's fromJson() method to de serialize your JSON.
You can better understand this by the example given below:
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class JsonToJava {
/**
* #param args
*/
public static void main(String[] args) {
String json = "[{\"firstName\":\"John\", \"lastName\":\"Doe\", \"id\":[\"10\",\"20\",\"30\"]},"
+ "{\"firstName\":\"Anna\", \"lastName\":\"Smith\", \"id\":[\"40\",\"50\",\"60\"]},"
+ "{\"firstName\":\"Peter\", \"lastName\":\"Jones\", \"id\":[\"70\",\"80\",\"90\"]},"
+ "{\"firstName\":\"Ankur\", \"lastName\":\"Mahajan\", \"id\":[\"100\",\"200\",\"300\"]},"
+ "{\"firstName\":\"Abhishek\", \"lastName\":\"Mahajan\", \"id\":[\"400\",\"500\",\"600\"]}]";
jsonToJava(json);
}
private static void jsonToJava(String json) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(json).getAsJsonArray();
ArrayList<POJO> lcs = new ArrayList<POJO>();
for (JsonElement obj : jArray) {
POJO cse = gson.fromJson(obj, POJO.class);
lcs.add(cse);
}
for (POJO pojo : lcs) {
System.out.println(pojo.getFirstName() + ", " + pojo.getLastName()
+ ", " + pojo.getId());
}
}
}
POJO class:
public class POJO {
private String firstName;
private String lastName;
private String[] id;
//Getters and Setters.
I hope this will solve your issue.
You are mixing datatypes. You cant have both an Array and a string. Change
"tags": ""
to
"tags": null
and you are good to go.
Use Jacskon Object Mapper
See below simple example
[http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/][1]
Jackson type safety is way better than Gson. At times you will stackoverflow in Gson.
I have the followed snipets of Json String:
{
"networks": {
"tech11": {
"id": "1",
"name": "IDEN"
},
"tech12": {
"id": "2",
"name": "EVDO_B"
}
}
}
I use some methods to convert this String to Object:
private static Gson mGson = new Gson();
...
public static WebObjectResponse convertJsonToObject(String jsonString) {
WebObjectResponse webObjectResponse = null;
if(jsonString != null && jsonString.length() > 1){
webObjectResponse = mGson.fromJson(jsonString, WebObjectResponse.class);
}
return webObjectResponse;
}
Where WebObjectResponse is class that should represent above mentioned String.
Its not complicated if I get static fields.
But in my case the values have different names: tech11, tech12 ....
I can use #SerializedName but its works in specific cases like convert "class" to "class_".
As you see networks Object defined as list of tech Objects but with different post-fix.
public class WebObjectResponse{
private DataInfoList networks = null;
}
This is static implementation, i defined 2 values tech11 and tech12 but next response might be techXX
public class DataInfoList {
private DataInfo tech11 = null;
private DataInfo tech12 = null;
}
public class DataInfo {
private String id = null;
private String name = null;
}
What is the good way to convert current Json String to Object where list of elements are Objects too and have different names?
Thank you.
Use a Map!
I would do the following
public class WebObjectResponse {
private Map<String, DataInfo> networks;
}
public class DataInfo {
private String id = null;
private String name = null;
}
// later
Gson gson = new Gson();
String json = "{\"networks\": {\"tech11\": { \"id\": \"1\",\"name\": \"IDEN\" }, \"tech12\": { \"id\": \"2\", \"name\": \"EVDO_B\" } }}";
WebObjectResponse response = gson.fromJson(json, WebObjectResponse .class);
For each object in json networks, a new entry will be added to the Map field of your class WebObjectResponse. You then reference them by techXX or iterate through the keyset.
Assuming a structure like this
{
"networks": {
"tech11": {
"id": "1",
"name": "IDEN"
},
"tech12": {
"id": "2",
"name": "EVDO_B"
},
"tech13": {
"id": "3",
"name": "WOHOO"
}, ...
}
}
We would need your class structure for more details.
As far as I am aware, I think you will need to have some mappings defined somewhere (I used xml's) and then try to match json with one of the mappings to create objects.
Google gson is good. I did it in Jackson
Also, converting objects should be trivial. But since you might have variable fields like tech11 and tech12 , you might want to store the "network" value as a string and then extract fields out of it when required.
Hope I could help.
Edit : Sotirious nails it.
Please use this link for converting SON Response to Java POJO class
http://www.jsonschema2pojo.org/