简体   繁体   中英

Custom serialize part of a POJO using Gson

I have a POJO for example like this:

class SurveyResult {
   public String name;
   public List<QuestionAnswer> questions;
}
class QuestionAnswer {
   public String key;
   public String question;
   public boolean answer;
}

I get the list of questions from the server so I don't know beforehand what they might be. When sending the SurveyResult back up to the server I need to send the following Json:

{ "name": "John Doe", "question1key" : true, "question2key" : false }

As you can see the list of QuestionAnswer is flattened to the same level as the SurveyResult.name . When building a custom serializer how can I achieve this? I know I can possibly do it by custom serializing the entire SurveyResult object but in the real world case there may be a lot of fields and I don't want to have to custom serialize all those fields just to flatten the list.

Thanks!

If you only want Gson, disregard this answer. Here I implemented a solution using Oson serializer and jsonNoName, requires 1.0.8

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