简体   繁体   中英

deserializing the content of a json array in a class shows null values using gson

I am trying to deserialize the content of a json array with name topics. after deserialing into the pojo, the topics array keeps printing null even though everything seems fine

//entry model

public class MainRequest {

    private  String bookId;
    private List<topics> topics; //called as a list based on the json structure
    
    }

//topics model

public class topics {
    private String DESCRIPTION;
    private String INDEX;
}

the two models is executed in a controller this way

@PostMapping(path = "/do-library-request", consumes = "application/json")
    public ResponseEntity<?> process(@RequestBody List<MainRequest> mainRequest,
                                                 HttpServletRequest request
    ) {

        Gson gsons = new Gson();
        
        logger.log(Level.INFO, "Request: {0}", gsons.toJson(mainRequest));
        
        //out from logger
        {"bookId":"155","topics":[{},{}]} // topics are null and this is the problem
                
        .......
    

how can I print the value of the topics is the challenge

[{

       "bookId":"155",       

       "topics":[

          {

             "DESCRIPTION":"Little Beginnings",

             "INDEX":"3455"

          },

          {

             "DESCRIPTION":"Nostalgic moments",

             "INDEX":"1234567"

          }

       ],

Change the variable names of class topic to lower case and add the SerializedName annotation

@Data
public class topics {
    @SerializedName("DESCRIPTION")
    private String description;
    @SerializedName("INDEX")
    private String index;
}

This should solve your problem. BTW: especialy at this point it is important to follow the java naming convetions

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