简体   繁体   中英

Sending custom JsonObject with child object to server fails

I am trying to POST an object from my Android client to my Play Framework Java REST API to persist to the database.

I am using Retrofit to perform API calls, and Realm for local device storage. JSON is handled using the Gson library in the client device.

I have a custom class to convert my object to JSON before sending, because if I don't do this, any child objects will include extra information such as columnInfo which will not be recognised on the server and it will not be able to convert the object to it rightful entity.

Server Stacktrace message

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "columnInfo" (class models.UserTbl), not marked as ignorable (5 known properties: "dateCreated", "id", "name", "email", "dateUpdated"])

Custom Serialization class

public class UserBookSerializer implements JsonSerializer<UserBook> {
    @Override
    public JsonElement serialize(UserMovie src, Type typeOfSrc, JsonSerializationContext context) {
        final JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id", src.getId());
        jsonObject.addProperty("bookId", src.getBookId());
        jsonObject.addProperty("user", String.valueOf(context.serialize(src.getUser()))); // here is the issue
        jsonObject.addProperty("isSaved", src.isSaved());

        return jsonObject;
    }
}

Above is my attempt, however it has not been successful. Does anybody know how to resolve this issue?

You can serialize classes really easy with gson, let's say that's the Json you want to get on the server

{  
  "name":"never",
  "age":5,
  "data":{  
    "id":"2fds4",
    "locale":"us"
  }
}

You write the following structure

class User {
   String name;
   long age;
   Data data;
}

class Data {
   String id;
   String locale;
}

then you just pass the instance of User to your retrofit, it will serialize it.

You can edit the class UserMovie and use Gson's @Expose annotation to explicitly mark the attributes you want to send. It should be used along with GsonBuilder.excludeFieldsWithoutExposeAnnotation() when you create the Retrofit instance.

https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/annotations/Expose.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM