Gson deserialisation generates NULL value

前端 未结 2 1013
栀梦
栀梦 2021-01-22 04:00

I was trying to read and convert a JSON file to an array but getting null values from the array after reading the JSON file. I am using the default constructor for my Ship

相关标签:
2条回答
  • 2021-01-22 04:39

    You can use something along these lines. Note that you don´t have to use Files.readAllBytes but in your code it could also be that the BufferedReader causes the error. If you need your ShipDetails as Array instead of a list, convert it or use your needed type in the TypeToken.

    final GsonBuilder builder = new GsonBuilder();
    final Gson gson = builder.enableComplexMapKeySerialization().create();
    
    // you can use the buffered reader here too, but this is easier to debug if shipDetails is a file
    final String jsonRepresentation = new String(Files.readAllBytes(shipDetails);
    
    // add a type definition
    final Type type = new TypeToken<ArrayList<ShipDetail>>(){}.getType();
    ArrayList<ShipDetail> shipDetails = gson.fromJson(jsonRepresentation, type);
    

    And as mentioned in the comments above, generate Getters and Setters.

    0 讨论(0)
  • 2021-01-22 04:51

    Your Gson mapping does not match the given JSON. By default, Gson maps JSON properties to their appropriate fields in the target mapping by exact name. Take a look at:

    "idmessage":"27301"
    

    and

    private String IdMessage
    

    The property name case and the field name case do not match. What you need is map your JSON correctly. Either:

    private String idmessage
    

    or by overriding the name match (and that's more appropriate for the Java naming conventions):

    @SerializedName("idmessage")
    private String idMessage;
    

    Note one field per line. This is required in order to annotated each field separately. Or, if possible, use camelCase both in Java and JSON.

    0 讨论(0)
提交回复
热议问题