logo
down
shadow

GSON serialize multiple properties to sub object


GSON serialize multiple properties to sub object

By : Ghost
Date : November 23 2020, 09:01 AM
will be helpful for those in need I've been experimenting with Retrofit and GSON in my project and came across an unusual case where I'm trying to convert two properties from JSON into a sub object using GSON on Android. , I suggest two approaches.
Let a class act as a bridge builder
code :
class InventoryItemBuilder {
    @SerializedName("cat1_id")   private int    catOneId;
    @SerializedName("cat1_name") private String catOneName;
    @SerializedName("cat2_id")   private int    catTwoId;
    @SerializedName("cat2_name") private String catTwoName;

    public InventoryItem buildInventoryItem() {
        Category c1 = new Category(catOneId, catOneName);
        Category c2 = new Category(catTwoId, catTwoName);
        return new InventoryItem(c1, c2);
    }
}
//InventoryItem{category1=Category{id=1111, name='First Category'}, category2=Category{id=2222, name='Second Category'}}
InventoryItem inventoryItem = new Gson().fromJson(json, InventoryItemBuilder.class).buildInventoryItem();
class InventoryItemDeserializer implements JsonDeserializer<InventoryItem> {
    @Override
    public InventoryItem deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jObject = json.getAsJsonObject();
        Category c1 = new Category(jObject.get("cat1_id").getAsInt(), jObject.get("cat1_name").getAsString());
        Category c2 = new Category(jObject.get("cat2_id").getAsInt(), jObject.get("cat2_name").getAsString());
        return new InventoryItem(c1, c2);
    }
}
Gson gson = new GsonBuilder().registerTypeAdapter(InventoryItem.class, new InventoryItemDeserializer()).create();
InventoryItem inventoryItem = gson.fromJson(json, InventoryItem.class);


Share : facebook icon twitter icon
Serialize object using GSON

Serialize object using GSON


By : David Xu
Date : March 29 2020, 07:55 AM
I wish this helpful for you You have configured Gson object using excludeFieldsWithoutExposeAnnotation method. From documentation:
Serialize response object with generic nested data object with GSON

Serialize response object with generic nested data object with GSON


By : Emmanuel
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Now I have solved it with an different approach:
2 response models for list and object:
code :
public class ApiResponse<T> {
    private int success;
    private String[] errors;
    private String[] messages;
    private T data;
}

public class ApiListResponse<T> {
    private int success;
    private String[] errors;
    private String[] messages;
    private List<T> data;
}
public class ResponseDeserializer<T> implements JsonDeserializer {
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
    JsonElement data = je.getAsJsonObject().get("data");
    GsonBuilder gsonBuilder = new GsonBuilder()
            .setExclusionStrategies(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getDeclaringClass().equals(RealmObject.class);
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            });
    Gson gson = gsonBuilder.create();
    T response = gson.fromJson(je, type);
    return response;
}
}
gsonBuilder.registerTypeAdapter(new TypeToken<ApiResponse<Object1>>() {}.getType(), new ResponseDeserializer<ApiResponse>());
gsonBuilder.registerTypeAdapter(new TypeToken<ApiListResponse<Object1>>() {}.getType(), new ResponseDeserializer<ApiListResponse>());
{  
   "data":{  
      "Object1Id":"1",
      "Name":"Test 1",
   },
   "messages":[  
   ],
   "errors":[  
   ],
   "success":"1"
}
{  
   "data":[{  
      "Object1Id":"1",
      "Name":"Test 1",
   },{  
      "Object1Id":"2",
      "Name":"Test 2",
   }],
   "messages":[  
   ],
   "errors":[  
   ],
   "success":"1"
}
GSON serialize sub Object

GSON serialize sub Object


By : BCM
Date : March 29 2020, 07:55 AM
it should still fix some issue I want to serialize this JSON structure : , I resolve my case like that :
JSON :
code :
{  
   "name":"name 1",
   "number":1,
   "standing":[  
      {  
         "subRank":1,
         "subname":"test"
      },
      {  
         "subRank":2,
         "subname":"Test2"
      }]
}
public class ParentClass{
    String name;
    int number;
    List<SubClass> standing;
}

public class SubClass{
    int subRank;
    String subname;
}
Gson gson = new Gson();
Type type = new TypeToken<ParentClass>() {}.getType();
ParentClass parentClassList= gson.fromJson(data, type);
How to serialize a special json with Gson (content of object instand of object)

How to serialize a special json with Gson (content of object instand of object)


By : tackler_of_vows
Date : March 29 2020, 07:55 AM
Hope that helps I find a solution with use Gson tools (class UserAddressAdapter extends TypeAdapter).
code :
public class User {

    ...

    // see the first ligne of UserAddressAdapter#write
    // city => (out.value(value.getCity());)
    @SerializedName("city")
    @JsonAdapter(UserAddressAdapter.class)
    private final UserAddress userAddress;
    ...

}


public class UserAddressAdapter extends TypeAdapter<UserAddress> {

    @Override
    public void write(JsonWriter out, UserAddress value) throws IOException {
        out.value(value.getCity());
        out.name("country");
        out.value(value.getCountry());
        out.name("houseNumber");
        out.value(value.getHouseNumber());
        out.name("street");
        out.value(value.getStreet());
    }

    @Override
    public UserAddress read(JsonReader in) throws IOException {
        final int city = in.nextInt();
        UserAddress[] scopes = UserAddress.values();
        for (UserAddress scope : scopes) {
            if (scope.getCity() == city) {
                return scope;
            }
        }
        return null;
    }

}
new Gson().toJson(new User("...", ...))
Java Gson Serialize and Deserialize object inside HashMap(key, Object)

Java Gson Serialize and Deserialize object inside HashMap(key, Object)


By : Matthew Lankford
Date : March 29 2020, 07:55 AM
wish helps you Object is deserialized into com.google.gson.internal.LinkedTreeMap, so tell Gson that you want the A class.
Related Posts Related Posts :
  • My shape moved but will pause for a while
  • How to solve syntax error in eclipse Mars.1
  • Shibboleth idp configuration for ldap authentication
  • Do something when app starts?
  • Android Runtime Exception font asset not found
  • How to query using objectify in Google App Engine app
  • List value is printing address instead of value
  • StringUtils.isBlank return false for null Strings
  • Sent parameter through PATCH android
  • i am not able to clear the code below given using throwable concept in java
  • How to get System time instead of Server time in java?
  • How to push json data into an arrya object in MONGO DB by java
  • Saving RelationshipEntity not working
  • Error on "instanceOf" when checking a subClass
  • Java - Splitting a image into 4 images
  • "Pinging" a server in Java
  • RoboGuice Proguard CreationException
  • Android Array list returns Null after adding values
  • Jar Executable what am I doing wrong?
  • How do I mitigate Connection leak triggered for connection com.mysql.jdbc.JDBC4Connection@11d08960,
  • How do i iterate values from a 2d array using conditions
  • Hide Button in CustomPagerAdapter
  • Java GC: does it ever make sense to call super.finalize() in a class that only extends Object?
  • 64bit HashMap in Java
  • Hibernate wildcard query on two columns
  • Want to Generate Auto Login Program Using Java
  • Spring security Oauth 2 with ajax login and form login
  • Parse findInBackground doesn't add to global arraylist?
  • Remove random item from ArrayList
  • in SpringMVC getMessage from i18n properties in a function outside the controller
  • How do I add JCheckBox next to each name that has been entered into an arraylist from a JTextField?
  • Return node ID along with complete node
  • InvocationTargetException. Cannot cast class X to class X. When invoked in Scala Imain through spark-submit
  • how to print elements of a 1D array into a N x N box
  • How to map csv file to pojo class in java
  • How, in Java, to encode default vhost %2F in URL/URI so it doesn't get changed to slash and fail to work
  • Tomcat 5.5 https configuration in Windows Server 2008 64bit
  • Enabling FIPS 140-2 compliance mode in MULE ESB
  • How to pass String PackageName to PkgName under parseXML() and run XMLParser class as a new activity when click on list
  • Error while creating spring -hibernate configuration file
  • Hand off control between java threads
  • NoClassDefFoundError: scala/collection/Seq
  • Getting stack overflow error on one machine but not the other on the same code
  • How can I loop AsyncAjaxRequest in GWT?
  • Failed to find provider info for urbanairship.provider
  • Android ListView Adapter Crash issue/Duplicates
  • Displaying Splash screen only once on user preference
  • Loop List<WebElement> doesn't stop despite no more WebElements
  • Check if pattern exists in a String
  • Swing - Key Problems (Arrow Keys, Tab, etc.) in GUIs with TextComponents
  • Why the solution for binary search tree validity is not working?
  • Double encrypting 2048 RSA?
  • create junit test for runnable class
  • Unable to read and sort information from a text file in Java
  • My device isn't getting detected in android studio (driver issue)
  • Representing a Graph in Java
  • How to XML mapping using jxls
  • Quick Sort stackoverflow error for large arrays
  • Parsing Apache Tika XML Output returns Unknown Tag
  • java simple UI loop, can't find bug
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co