Using Gson fromJson method not working - java

I have a json string that is represented as below:
"{"RequestId":255,
"RequestTime":"2016-04-08T17:00:40.327",
"Otp":"123456",
"AppName":"This is my app name",
"IsAwaitingResponse":false}"
I also have a class object below that I wish to create using the Gson library fromJson() method...
public class AccessRequest{
public int Id;
public String RequestTime;
public String Otp;
public String AppName;
public Boolean IsAwaitingResponse;
}
Now when I call the gson.fromJson method it does not error but my object is not getting set. This is the code I'm using...
Gson gson = new Gson();
AccessRequest ar;
ar = gson.fromJson(jsonString, AccessRequest.class);
It is instead setting my 'ar' variable to some strange gson object that clearly is wrong but no error is thrown.
{serializeNulls:falsefactories:[Factory[typeHierarchy=com.google.gson.JsonElement,adapter=com.google.gson.internal.bind.TypeAdapters$25#e8dad0a],
From what I can see, there is no error in my Json string ( although I am new to json ) , so I'm not really sure why this method wouldn't be working...

You probably printed the gson object instead of the ar object, as #Pillar noted in the comments.
I've tried your example and it works as expected. Also, the Id field is not being set because the name of the property does not match. You should use #SerializedName or change any of the names. This has also been noted in the comments.
This is the working example:
package net.sargue.gson;
import com.google.gson.Gson;
import org.intellij.lang.annotations.Language;
public class SO36553536 {
public static void main(String[] args) {
#Language("JSON")
String json = "{\n" +
" \"RequestId\": 255,\n" +
" \"RequestTime\": \"2016-04-08T17:00:40.327\",\n" +
" \"Otp\": \"123456\",\n" +
" \"AppName\": \"This is my app name\",\n" +
" \"IsAwaitingResponse\": false\n" +
"}";
Gson gson = new Gson();
AccessRequest ar;
ar = gson.fromJson(json, AccessRequest.class);
System.out.println("ar.getClass() = " + ar.getClass());
System.out.println("ar = " + ar);
}
public class AccessRequest {
public int Id;
public String RequestTime;
public String Otp;
public String AppName;
public Boolean IsAwaitingResponse;
#Override
public String toString() {
return "AccessRequest{" + "Id=" + Id +
", RequestTime='" + RequestTime + '\'' +
", Otp='" + Otp + '\'' +
", AppName='" + AppName + '\'' +
", IsAwaitingResponse=" + IsAwaitingResponse +
'}';
}
}
}
And this is the execution output:
ar.getClass() = class net.sargue.gson.SO36553536$AccessRequest
ar = AccessRequest{Id=0
, RequestTime='2016-04-08T17:00:40.327'
, Otp='123456'
, AppName='This is my app name'
, IsAwaitingResponse=false}

As just need to change RequestId from Id class AccessRequest.
you will get proper output.

Related

Deserialize inner object of deserialized object using gson

We are deserializing top-level RefundAttrs attribute while fetching transaction object from DB. I cannot change this part.
How can I deserialize RefundAttrs.metadata field into RefundEventData? I am getting com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 52 path $.reason
class RefundAttrs {
private String instrumentTxnId;
private Object metadata;
public String instrumentTxnId() {
return instrumentTxnId;
}
public Object metadata() {
return metadata;
}
#Override
public String toString() {
return String.format("{ instrumentTxnId=%s, metadata=%s }", this.instrumentTxnId, this.metadata);
}
}
class RefundEventData {
private String orderId;
private Double refundAmount;
private String reason;
#Override
public String toString() {
return String.format("{ orderId=%s, refundAmount=%s, reason=%s }", this.orderId, this.refundAmount, this.reason);
}
}
public static void main(String[] args) throws IOException {
Gson gson = new Gson();
String json = "{\n" +
" \"instrumentTxnId\": \"refund-101\",\n" +
" \"metadata\": {\n" +
" \"orderId\": \"011-acf\",\n" +
" \"refundAmount\": 100.0,\n" +
" \"reason\": \"User left\"\n" +
" }\n" +
"}";
RefundAttrs attrs = gson.fromJson(json, RefundAttrs.class);
System.out.println(attrs.metadata());
// {orderId=011-acf, refundAmount=100.0, reason=User left}
RefundEventData eventData = gson.fromJson(attrs.metadata().toString(), RefundEventData.class);
}
attrs.metadata().toString() generates invalid JSON text.
Convert the metadata to JSON:
RefundEventData eventData = gson.fromJson(gson.toJson(attrs.metadata()), RefundEventData.class);

Unable to deserialise via mixin

Attached is my json. I am receiving this from an endpoint. I have the object type in my consuming app. the object contains; success, message and loggedInMember (which is an object). In the json, the feeClasses contains a lot of fields and objects etc which is why i have not included the whole json. I am only interested in the success and message fields.
{
"header":{
"messageId":null,
"receivedTimestamp":1611246394839,
"replyTo":null,
"redelivered":false,
"originator":null
},
"internalId":null,
"auditPoints":[
],
"success":true,
"message":"",
"loggedInMember":{
"feeClasses":{
...CONTAINS A LOT OF FIELDS...
}
}
}
I am trying to map this response to the object type, hence essentially leaving loggedInMembers null. This is my test I am trying to run:
public void test() throws JsonProcessingException
{
//String json = "{\"header\":{\"messageId\":null,\"bucketNumber\":null,\"senderSubId\":null,\"senderLocationId\":null,\"onBehalfOfCompId\":null,\"onBehalfOfSubId\":null,\"onBehalfOfLocationId\":null,\"correlationId\":null,\"receivedTimestamp\":1611246394839,\"replyTo\":null,\"redelivered\":false,\"originator\":null},\"internalId\":null,\"auditPoints\":[],\"success\":true,\"message\":\"\",\"loggedInMember\":{\"memberLoginName\":\"BMARTINTEST\",\"memberId\":\"201901241246290000036402D\",\"settlementAccountIds\":[\"201901241246290000036491D\"],\"parentMemberId\":\"1\",\"firmId\":\"990\",\"memberType\":\"INDIVIDUAL\",\"memberAccountType\":\"PROD\",\"password\":\"D1208B304FD7AA6187690A389A5040C1D9B07643\",\"feeClasses\":{\"byId\":{\"201902120947520000559606D\":{\"memberLoginName\":\"BMARTINTEST\",\"feeClassId\":\"201508041827550000942152D\",\"memberFeeClassId\":\"201902120947520000559606D\",\"allocatedDate\":{\"year\":2019,\"month\":2,\"day\":12,\"timeMillis\":1549929600000},\"firstUsedForTradeDate\":{\"year\":2019,\"month\":2,\"day\":12,\"timeMillis\":1549929600000},\"firstUsedForSettlementDate\":null,\"usableFromDate\":{\"year\":2019,\"month\":2,\"day\":12,\"timeMillis\":1549929600000},\"usableToDate\":{\"year\":2019,\"month\":2,\"day\":19,\"timeMillis\":1550534400000},\"usableToTimestamp\":1550613600000,\"usableBusinessDaysAllocated\":6,\"usableBusinessDaysRemaining\":0,\"narrative\":\"Bonus assigned to member at first-time funding of amount 4000.00 : Set expiration date/time\",\"disabled\":false,\"usableForTrade\":true,\"usableForSettlement\":true},\"202001290940390000868824D\":{\"memberLoginName\":\"BMARTINTEST\",\"feeClassId\":\"202001290940340000776406D\",\"memberFeeClassId\":\"202001290940390000868824D\",\"allocatedDate\":{\"year\":2020,\"month\":1,\"day\":29,\"timeMillis\":1580256000000},\"firstUsedForTradeDate\":null,\"firstUsedForSettlementDate\":null,\"usableFromDate\":{\"year\":2020,\"month\":1,\"day\":6,\"timeMillis\":1578268800000},\"usableToDate\":{\"year\":2020,\"month\":2,\"day\":27,\"timeMillis\":1582761600000},\"usableToTimestamp\":1582840800000,\"usableBusinessDaysAllocated\":0,\"usableBusinessDaysRemaining\":0,\"narrative\":\"Added NO_FEES_CLASS\",\"disabled\":false,\"usableForTrade\":true,\"usableForSettlement\":true},\"201901241246290000036417D\":{\"memberLoginName\":\"BMARTINTEST\",\"feeClassId\":\"201508041736360000943781D\",\"memberFeeClassId\":\"201901241246290000036417D\",\"allocatedDate\":{\"year\":2019,\"month\":1,\"day\":24,\"timeMillis\":1548288000000},\"firstUsedForTradeDate\":null,\"firstUsedForSettlementDate\":null,\"usableFromDate\":{\"year\":2019,\"month\":1,\"day\":24,\"timeMillis\":1548288000000},\"usableToDate\":null,\"usableToTimestamp\":null,\"usableBusinessDaysAllocated\":0,\"usableBusinessDaysRemaining\":0,\"narrative\":null,\"disabled\":false,\"usableForTrade\":true,\"usableForSettlement\":true}},\"empty\":false},\"legalName\":\"Martin Birch\",\"taxId\":\"345335454\",\"taxCountryId\":\"US\",\"currency\":\"USD\",\"lastTradeId\":null,\"introducingBrokerMemberId\":null,\"introducingBrokerMemberName\":null,\"introducingBrokerMemberCode\":null,\"clearedByMemberId\":\"SECOND_TEST\",\"clearedByMemberLoginName\":null,\"memberProblems\":[],\"emailNotificationEnabled\":true,\"rtafLevelId\":0,\"rtafAmount\":0,\"maxNumberOfPositionAccounts\":1,\"ciciIdentifier\":null,\"traderRequired\":false,\"interestClass\":\"INDIVIDUAL\",\"memberCreatedDate\":1548333989000,\"parentMemberLoginNames\":[\"NADEX.COM\",\"NADEX\"],\"demoStartDate\":null,\"demoEndDate\":null,\"clientIdMaxLimit\":null,\"memberAccountApplicationFieldData\":null,\"rank\":0,\"uuid\":\"201901241246290000036395D\",\"referrerId\":\"raf4qam5h00s36d\",\"testMember\":false},\"allReplyToSource\":[],\"sendToOriginatorOnly\":false}";
String json = "{\n" +
" \"header\":{\n" +
" \"messageId\":null,\n" +
" \"receivedTimestamp\":1611246394839,\n" +
" \"replyTo\":null,\n" +
" \"redelivered\":false,\n" +
" \"originator\":null\n" +
" },\n" +
" \"internalId\":null,\n" +
" \"auditPoints\":[\n" +
" \n" +
" ],\n" +
" \"success\":true,\n" +
" \"message\":\"\",\n" +
" \"loggedInMember\":{\n" +
" \"feeClasses\":{\n" +
" \n" +
" }\n" +
" }\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.addMixIn(LogonResponseMessage.class, LogonResponseMixin.class);
LogonResponseMessage responseMessage = objectMapper.readValue(json, LogonResponseMessage.class);
System.out.println(responseMessage);
}
My mixin:
public abstract class LogonResponseMixin
{
LogonResponseMixin(#JsonProperty("success") boolean success, #JsonProperty("message") String message){};
#JsonIgnore
abstract Member loggedInMember();
#JsonIgnore
abstract MemberFeeClasses feeClasses();
#JsonIgnore
abstract Header header();
}
I am getting the following error: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of domain.xyz.MemberFeeClasses (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
Am i creating the mixin wrong? I have asked in a previous question and using mixin was the general consensus but it doesn't seem to play ball with me.
Thank you.
The reason why MemberFeeClasses cannot be constructed is the same as your initial problem, just add a mixin for all classes
See the example below:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import java.io.IOException;
public class Test {
//------------------------------------------------//
// PART 1 - MAIN TEST METHOD
//------------------------------------------------//
public static void main(String[] args) throws IOException {
String json = "{\n" +
" \"header\":{" +
" },\n" +
" \"success\":true,\n" +
" \"message\":\"\",\n" +
" \"loggedInMember\":{\n" +
" \"feeClasses\":{\n" +
" \"amount\": \"20\"\n" +
" }\n" +
" }\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
//objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.addMixIn(LogonResponseMessage.class, LogonResponseMixin.class);
objectMapper.addMixIn(Member.class, MemberMixin.class);
objectMapper.addMixIn(MemberFee.class, MemberFeeMixin.class);
LogonResponseMessage responseMessage = objectMapper.readValue(json, LogonResponseMessage.class);
System.out.println(responseMessage.loggedInMember.feeClasses.amount);
}
//------------------------------------------------//
// PART 2 - CREATOR MIXIN
//------------------------------------------------//
static abstract class LogonResponseMixin {
LogonResponseMixin(#JsonProperty("success") boolean success,
#JsonProperty("message") String message,
#JsonProperty("header") Header header,
#JsonProperty("loggedInMember") Member member) {
}
}
static abstract class MemberMixin {
MemberMixin(#JsonProperty("feeClasses") MemberFee feeClasses) {
}
}
static abstract class MemberFeeMixin {
#JsonCreator
MemberFeeMixin(#JsonProperty("amount") String amount) {
}
}
//------------------------------------------------//
// PART 3 - EXAMPLE CLASS DEFINITION
//------------------------------------------------//
static class Header {
}
#Getter
#Setter
static class Member {
private MemberFee feeClasses;
public Member(MemberFee feeClasses) {
this.feeClasses = feeClasses;
}
}
#Getter
#Setter
static class MemberFee {
private String amount;
public MemberFee(String amount) {
this.amount = amount;
}
}
#Getter
#Setter
static class LogonResponseMessage {
private boolean success;
private String message;
private Header header;
private Member loggedInMember;
public LogonResponseMessage(boolean success, String message, Header header, Member member) {
this.success = success;
this.message = message;
this.header = header;
this.loggedInMember = member;
}
}
}

How can i deserialize Json string where object's field's subclass is included in json string, using Java and Jackson library

I am very new to Java. I have some classes Site, Instances, CloudInstance. Class Site has an attribute instances and class CloudInstance inherits class Instance. They are as follows-
public class Site extends BaseEntity {
private String siteName;
List<Instance> instances = Lists.newArrayList();
}
public class Instance extends BaseEntity {
private String instanceId;
private String name;
}
public class CloudInstance extends Instance {
private String availabilityZone;
private String instanceType
}
I am deserializing json string as follows -
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
BaseEntity obj = null;
obj = (BaseEntity) mapper.readValue(jsonStr, Site.class);
It works fine if my jsonStr does not contain fields of class 'CloudInstance' and contains field instance with Instance class's fields.
Problem - Now i want to deserialize the jsonStr which includes 'CloudInstance' classe's fiels as well as the part of 'instances' field of class 'Site'. Ex jsonStr is as follows -
{
"id": null,
"siteName": "demo",
"instances": [
{
"instanceId": "i-8c2ee5fc",
"name": "some-node",
"availabilityZone": "some-zone",
"instanceType": "t1.micro"
}]
}
For the above jsonStr i get following error
error: Unrecognized field \"availabilityZone\" and error: Unrecognized field \"instanceType\"
With lots of if else and dirty code i can get the obj of Site including above fields. But i want to implement clean solution for this.
Is there any library which can do this? Any help id valuable. Please help..!!
Thanks in advance.
What you are trying to achieve is called polymorphic deserialization. Your example fails because Jackson needs to know what instance type should be constructed from JSON and placed to the list of instances. Please refer to this wiki page for detailed explanation.
I have modified you example to demonstrate how it could work. I've added the instance type information in the #type field in the JSON representation. Also I've made all the classes immutable using constructors annotated with the #JsonCreator annotation to create instances.
public class JacksonPolymorphism {
public static class BaseEntity {
private final String id;
protected BaseEntity(String id) {
this.id = id;
}
}
public static class Site extends BaseEntity {
private final String siteName;
private final List<Instance> instances;
#JsonCreator
public Site(#JsonProperty("id") String id,
#JsonProperty("siteName") String siteName,
#JsonProperty("instances") List<Instance> instances) {
super(id);
this.siteName = siteName;
this.instances = instances;
}
#Override
public String toString() {
return "Site{" +
"siteName='" + siteName + '\'' +
", instances=" + instances +
'}';
}
}
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "#type")
#JsonTypeName(value = "simple")
public static class Instance extends BaseEntity {
private final String name;
#JsonCreator
public Instance(#JsonProperty("instanceId") String id,
#JsonProperty("name") String name) {
super(id);
this.name = name;
}
#Override
public String toString() {
return "Instance{" +
"name='" + name + '\'' +
'}';
}
}
#JsonTypeName("cloud")
public static class CloudInstance extends Instance {
private final String availabilityZone;
private final String instanceType;
public CloudInstance(#JsonProperty("instanceId") String id,
#JsonProperty("name") String name,
#JsonProperty("availabilityZone") String availabilityZone,
#JsonProperty("instanceType") String instanceType) {
super(id, name);
this.availabilityZone = availabilityZone;
this.instanceType = instanceType;
}
#Override
public String toString() {
return "CloudInstance{" +
"availabilityZone='" + availabilityZone + '\'' +
", instanceType='" + instanceType + '\'' +
'}';
}
}
public static final String JSON = "{\n" +
" \"id\": null,\n" +
" \"siteName\": \"demo\",\n" +
" \"instances\": [\n" +
" {\n" +
" \"#type\": \"cloud\",\n" +
" \"instanceId\": \"i-8c2ee5fc\",\n" +
" \"name\": \"some-node\",\n" +
" \"availabilityZone\": \"some-zone\",\n" +
" \"instanceType\": \"t1.micro\" \n" +
" }," +
" {\n" +
" \"#type\": \"simple\",\n" +
" \"instanceId\": \"ABC\",\n" +
" \"name\": \"FGF\"\n" +
" }]" +
" }";
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerSubtypes(CloudInstance.class);
System.out.println(mapper.readValue(JSON, Site.class));
}
}
Output:
Site{siteName='demo', instances=[CloudInstance{availabilityZone='some-zone', instanceType='t1.micro'}, Instance{name='FGF'}]}
I always had problems to deserialize JSON that contains List<...> objects with Jackson, so try to deserialize with Gson:
https://code.google.com/p/google-gson/
Take a look at the documentation in the methods fromJson and toJson.
I hope that can help,
Best regards
Never had consistent luck with Jackson or Gson, try Flex JSON instead:
JSONSerializer ser = new JSONSerializer();
String json = ser.deepSerialize(yourObject);
JSONDeserializer<YourMainType> der = new JSONDeserializer<YourMainType>();
YourMainType mainType = der.deserialize(json);
For this to work, all classes subject to serialization/deserialization must expose getters/setters consistent with Java Beans convention.
You can used GSON Library for de-serialize your Json into your class object.
There is function gson.fromJson(JSON String) which convert json string to class object.
Here is Sample code :
Gson json = new Gson();
Site site = json.fromJson(jsonStr, Site.class);
But in your code you have replace
List<Instance> instances = Lists.newArrayList();
this line in class Site with
List<CloudInstance> instances = new ArrayList<CloudInstance>();
Because your CloudInstance class extend Instance it means CloudInstance class include member of Instance class. As per json you need to do this to cast directly into class object.
May this will help you.

GSON: Deserializing Json with random class names

I'm trying to use GSON to deserialize some Json to a nice, tidy object. Now, I have managed to get the Json to correctly map to some of the more obvious variables. However, while trying to map some of the Json I came across this:
{
"this_number": 1,
"that_number": 12,
"some_string": "String!",
"list_of_objects": {
"342356676784653234535345": {
"random_double": "0.1235667456456",
"magic": "29",
"health": 1,
"price": 7,
"point": {
"x": 2,
"y": 70
}
},
"2345263767467354": {
"random_double": "0.1235667456456",
"magic": "23",
"health": 1,
"price": 9,
"point": {
"x": 0,
"y": 70
}
}
}
}
It was mapping nicely until I came to "list_of_objects". I can't for the life of me work out how to implement it. I think the main issue is that they are no longer static class names, they are randomized. Therefore it would be totally impractical (and impossible) to write something like:
class 342356676784653234535345{
double random_double = 0.0;
//etc
}
I've had a look around Stackoverflow, but the answers seem quite complex and many don't quite answer what I'm wanting to know.
I have played around with the plain Object method used here, but I couldn't find any further information on its usage.
I also keep finding references to mapping to generic types, but I don't quite understand what is going on. For example
You can convert a JSON string to an equivalent Java object using custom Gson JsonDeserializer
Assuming you have mapping classes
public class Data {
private int this_number;
private int that_number;
private String some_string;
private List<DataInfo> objects;
}
public class DataInfo {
private double random_double;
private int magic;
private int health;
private int price;
}
public class Point {
int x ;
int y;
}
CustomDeserializer
public class CustomDeserializer implements JsonDeserializer<Data> {
#Override
public Data deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
final int this_number = jsonObject.get("this_number").getAsInt();
final int that_number = jsonObject.get("that_number").getAsInt();
final String some_string = jsonObject.get("some_string").getAsString();
JsonObject list_of_objects =jsonObject.get("list_of_objects").getAsJsonObject();
Set<Entry<String, JsonElement>> objects = list_of_objects.entrySet();
final Data data = new Data();
List<DataInfo> list = new ArrayList<>();
Gson gson = new Gson();
for (Entry<String, JsonElement> entry : objects) {
JsonElement jsonElement = entry.getValue();
DataInfo info = gson.fromJson(jsonElement,DataInfo.class);
list.add(info);
}
data.setObjects(list);
data.setSome_string(some_string);
data.setThat_number(that_number);
data.setThis_number(this_number);
return data;
}
}
Just define
Map<String, Inner> list_of_objects;
in your outer class and let Gson do the work for you. It will deserialize nicely without effort. To make things clearer I did a full example based on your data. Just copy/paste/build/run this class. Your data structures are defined as static inner classes for my convenience, you can put them into separate files.
package stackoverflow.questions.q23472175;
import java.util.Map;
import com.google.gson.Gson;
public class Q23472175 {
private static class Point {
int x;
int y;
#Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
private static class Inner {
String random_double;
String magic;
int health;
int price;
Point point;
#Override
public String toString() {
return "Inner [random_double=" + random_double + ", magic=" + magic + ", health=" + health + ", price=" + price + ", point=" + point + "]";
}
}
private static class Outer {
int this_number;
int that_number;
String some_string;
Map<String, Inner> list_of_objects;
#Override
public String toString() {
return "Outer [this_number=" + this_number + ", that_number=" + that_number + ", some_string=" + some_string + ", list_of_objects=" + list_of_objects + "]";
}
}
public static void main(String[] args) {
String json = "{"+
" \"this_number\": 1,"+
" \"that_number\": 12,"+
" \"some_string\": \"String!\","+
" \"list_of_objects\": {"+
" \"342356676784653234535345\": {"+
" \"random_double\": \"0.1235667456456\","+
" \"magic\": \"29\","+
" \"health\": 1,"+
" \"price\": 7,"+
" \"point\": {"+
" \"x\": 2,"+
" \"y\": 70"+
" }"+
" },"+
" \"2345263767467354\": {"+
" \"random_double\": \"0.1235667456456\","+
" \"magic\": \"23\","+
" \"health\": 1,"+
" \"price\": 9,"+
" \"point\": {"+
" \"x\": 0,"+
" \"y\": 70"+
" }"+
" }"+
" }"+
"}";
Gson g = new Gson();
Outer object = g.fromJson(json, Outer.class);
System.out.print(object);
}
}
This is the result:
Outer [this_number=1, that_number=12, some_string=String!, list_of_objects={342356676784653234535345=Inner [random_double=0.1235667456456, magic=29, health=1, price=7, point=Point [x=2, y=70]], 2345263767467354=Inner [random_double=0.1235667456456, magic=23, health=1, price=9, point=Point [x=0, y=70]]}]

Parse JSON with Gson

How can I parse the JSON below with Gson?
Now I use:
private AttachChildDataModel parseSuccess(String content){
Gson gson = new Gson();
return gson.fromJson(content, AttachChildDataModel.class);
}
Where AttachChildDataModel has these member variables:
private Integer adultId;
private Integer childId;
private PlatformEnum platform;
private String regId;
private Date loginDate;
private Date logoutDate;
private ClientApp clientApp;
The Json string I'm trying to parse is:
{"log":
{
"childId":2,
"adultId":1,
"logoutDate":null,
"platform":"IPHONE",
"regId":null,
"loginDate":1325419200000,
"clientApp":"CHILD_APP"
}
}
When I put the object into the Spring ModelView, I add it under name log. The problematic thing is when I try to parse it with Gson. Right now, I manually remove the "log" prefix and the "}" postfix with String#substring, but I think there's a better solution.
To solve your problem, just create a "foo" class like this:
package stackoverflow.questions.q15614008;
public class Foo {
public AttachChildDataModel log;
}
and use it as base class for parsing in Gson:
package stackoverflow.questions.q15614008;
import com.google.gson.*;
public class Q15614008 {
public static void main(String[] arg) {
String testString = "{\"log\": "
+ " {"
+ "\"childId\":2," + "\"adultId\":1,"
+ "\"logoutDate\":null,"
+ "\"platform\":\"IPHONE\","
+ "\"regId\":null,"
+ "\"loginDate\":1325419200000,"
+ "\"clientApp\":\"CHILD_APP\"}"
+ "}";
Gson gson = new Gson();
Foo foo = gson.fromJson(
testString, Foo.class);
System.out.println("Result: " + foo.log.toString());
}
}
Then use only the log member variable of the Foo class.

Categories

Resources