Gson转换返回null java对象

时间:2016-07-09 04:47:05

标签: java android json gson

我正在尝试使用Gson在java bean中转换json字符串,但它是returnig null值。

public static void convert(String args) {
    String json =
                "{"body":{"response":{"total":"294","num":"294","filelist":[{"id":"56712","camname":"Camera1","camid":"514","start":"2016-07-08 12:00:38","end":"2016-07-08 12:03:00","stream":"3","recReason":"Activity","filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.jpg","nvrip":"192.168.0.200:8095"},{"id":"56708","camname":"Camera1","camid":"514","start":"2016-07-08 11:58:14","end":"2016-07-08 12:00:36","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.jpg","nvrip":"192.168.0.200:8095"},{"id":"56705","camname":"Camera1","camid":"514","start":"2016-07-08 11:55:49","end":"2016-07-08 11:58:11","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.mrv","snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.jpg","nvrip":"192.168.0.200:8095"},{"id":"56702","camname":"Camera1","camid":"514","start":"2016-07-08 11:53:25","end":"2016-07-08 11:55:47","stream":"3","recReason":"Activity","filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.mrv","snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.jpg","nvrip":"192.168.0.200:8095"},{"id":"56699","camname":"Camera1","camid":"514","start":"2016-07-08 11:51:00","end":"2016-07-08 11:53:22","stream":"3","recReason":"Activity","filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.mrv","snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.jpg","nvrip":"192.168.0.200:8095"}],"status":"OK"}}}";

    // Now do the magic.
    RecordingListResponseDTO data = new Gson().fromJson(json, RecordingListResponseDTO .class);

    // Show it.
    System.out.println("converted data :"+data);
}

My Bean Class正在关注。 的 RecordingListResponseDTO

   public class RecordingListResponseDTO implements Serializable {
    private String status;
    private int total;
    private int num;
    List<FileListDTO> fileList;

    public RecordingListResponseDTO(){

    }
    public RecordingListResponseDTO(String status, int total, int num, List<FileListDTO> fileList) {
        this.status = status;
        this.total = total;
        this.num = num;
        this.fileList = fileList;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public List<FileListDTO> getFileList() {
        return fileList;
    }

    public void setFileList(List<FileListDTO> fileList) {
        this.fileList = fileList;
    }

    @Override
    public String toString() {
        return "RecordingListResponseDTO{" +
                "status='" + status + '\'' +
                ", total=" + total +
                ", num=" + num +

                ", fileList=" + fileList +
                '}';
    }}

FileListDTO.java

public class FileListDTO {
private int id;
private String camname;
private int camid;
private Date start;
private Date end;
private int stream;
private String recReason;
private String filename;
private String snapshot;
private String nvrip;

public FileListDTO(int id, String camname, Date start, int camid, Date end, int stream, String recReason, String filename, String snapshot, String nvrip) {
    this.id = id;
    this.camname = camname;
    this.start = start;
    this.camid = camid;
    this.end = end;
    this.stream = stream;
    this.recReason = recReason;
    this.filename = filename;
    this.snapshot = snapshot;
    this.nvrip = nvrip;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getCamname() {
    return camname;
}

public void setCamname(String camname) {
    this.camname = camname;
}

public int getCamid() {
    return camid;
}

public void setCamid(int camid) {
    this.camid = camid;
}

public Date getStart() {
    return start;
}

public void setStart(Date start) {
    this.start = start;
}

public Date getEnd() {
    return end;
}

public void setEnd(Date end) {
    this.end = end;
}

public int getStream() {
    return stream;
}

public void setStream(int stream) {
    this.stream = stream;
}

public String getRecReason() {
    return recReason;
}

public void setRecReason(String recReason) {
    this.recReason = recReason;
}

public String getFilename() {
    return filename;
}

public void setFilename(String filename) {
    this.filename = filename;
}

public String getSnapshot() {
    return snapshot;
}

public void setSnapshot(String snapshot) {
    this.snapshot = snapshot;
}

public String getNvrip() {
    return nvrip;
}

public void setNvrip(String nvrip) {
    this.nvrip = nvrip;
}

@Override
public String toString() {
    return "FileListDTO{" +
            "id=" + id +
            ", camname='" + camname + '\'' +
            ", camid=" + camid +
            ", start=" + start +
            ", end=" + end +
            ", stream=" + stream +
            ", recReason='" + recReason + '\'' +
            ", filename='" + filename + '\'' +
            ", snapshot='" + snapshot + '\'' +
            ", nvrip='" + nvrip + '\'' +
            '}';
}}

将Json字符串转换为Java对象后,我得到null值。 我建议你做错了。 提前谢谢。

2 个答案:

答案 0 :(得分:2)

<强>先决条件:

使用了以下JSON:

{
   "body":{
      "response":{
         "total":294,
         "num":294,
         "filelist":[
            {
               "id":56712,
               "camname":"Camera1",
               "camid":514,
               "start":"2016-07-08 12:00:38",
               "end":"2016-07-08 12:03:00",
               "stream":3,
               "recReason":"Activity",
               "filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.mrv",
               "snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_12_00_57.jpg",
               "nvrip":"192.168.0.200:8095"
            },
            {
               "id":56708,
               "camname":"Camera1",
               "camid":514,
               "start":"2016-07-08 11:58:14",
               "end":"2016-07-08 12:00:36",
               "stream":3,
               "recReason":"Activity",
               "filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.mrv",
               "snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_58_33.jpg",
               "nvrip":"192.168.0.200:8095"
            },
            {
               "id":56705,
               "camname":"Camera1",
               "camid":514,
               "start":"2016-07-08 11:55:49",
               "end":"2016-07-08 11:58:11",
               "stream":3,
               "recReason":"Activity",
               "filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.mrv",
               "snapshot":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_56_08.jpg",
               "nvrip":"192.168.0.200:8095"
            },
            {
               "id":56702,
               "camname":"Camera1",
               "camid":514,
               "start":"2016-07-08 11:53:25",
               "end":"2016-07-08 11:55:47",
               "stream":3,
               "recReason":"Activity",
               "filename":"fs-1/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.mrv",
               "snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_53_44.jpg",
               "nvrip":"192.168.0.200:8095"
            },
            {
               "id":56699,
               "camname":"Camera1",
               "camid":514,
               "start":"2016-07-08 11:51:00",
               "end":"2016-07-08 11:53:22",
               "stream":3,
               "recReason":"Activity",
               "filename":"fs/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.mrv",
               "snapshot":"fs-/514/2016-07-08/AD_1_1_3_2016_07_08_11_51_19.jpg",
               "nvrip":"192.168.0.200:8095"
            }
         ],
         "status":"OK"
      }
   }
}

第1步:

修改private List<FileListDTO> fileListRecordingListResponseDTO.java的声明,如下所示:

@SerializedName("filelist")
private List<FileListDTO> fileList

第2步:

定义以下课程MyDateTypeAdapter.java

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class MyDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {

    private DateFormat dateFormat;

    public MyDateTypeAdapter() {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); 
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); 
    }

    @Override
    public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(dateFormat.format(date));
    }

    @Override
    public synchronized Date deserialize(JsonElement jsonElement, Type type,
            JsonDeserializationContext jsonDeserializationContext) {
        try {
            return dateFormat.parse(jsonElement.getAsString());
        } catch (ParseException e) {
            throw new JsonParseException(e);
        }
    }

}

第3步:

修改方法convert(String args),如下所示:

public static void convert(String args) {
        JsonParser parser = new JsonParser();
        String json = parser.parse(args)
                            .getAsJsonObject()
                            .getAsJsonObject("body")
                            .getAsJsonObject("response")
                            .toString();

        // Now do the magic.
        RecordingListResponseDTO data = new GsonBuilder()
                 .registerTypeAdapter(Date.class, new MyDateTypeAdapter())
                .create().fromJson(json, RecordingListResponseDTO.class);
        // Show it.
        System.out.println("converted data :"+data);
}

出于测试目的,您可以尝试将JSON存储在文件中,即D:/test.json,并通过以下方式调用方法:

String json = new String(Files.readAllBytes(Paths.get("D:/test.json")));
convert(json); 

答案 1 :(得分:1)

您需要更改模型类,

最初在你的json响应中,数据包含代表object的“body”标签,最初需要为object标签创建类,然后所有数据都包含在你的“body”标签内,所以解析了body数据里面的所有数据,

可能有助于此代码,

public class RecordingListResponseDTO implements Serializable {
  Recordinglist body;

  public class Recordinglist(){
    Recordresponse response;

     public class Recordresponse(){
       String total;

       public int getTotal() {
          return total;
       }

       public void setTotal(int total) {
          this.total = total;
       }
    }
  }
}