用于嵌套pojo的自定义gson反序列化器

时间:2017-06-22 10:27:00

标签: java json gson deserialization android

如何使用当前json对象中的字段并将其传递给下一个对象的自定义构造函数。如果我使用gson使用默认反序列化,它适用于具有相同名称的字段,但由于我的房间pojo有字段streetName和houseName(我想存储它所属的房子和街道),我想添加反序列化。我该怎么做呢?我有一个json,看起来像这样:

{
  "database": {
    "name": "",
    "email": "",
    "password": "",
    "streets": {
      "streetName1": {
        "houseName1": {
          "room1": {
            "roomMembers": 3
          }
        },
        "houseName2": {
          "room2": {
            "roomMembers": 2
          }
        }
      },
      "streetName2": {
        "houseName3": {
          "room3": {
            "roomMembers": 1
          },
          "room4": {
            "consumption": ""
          }
        }
      }
    }
  }
}

我的pojos如下:

Street.java

    public class Street{
    String streetName;
    List<House> houseList;


   ///getters and setters
    }

House.java

    public class House{
    String houseName;
    String streetName; //this is what I want to set using a different constructor
    List<Room> roomList;


   ///getters and setters
    }

Room.java

public class Room{
String roomName;    
String houseName;//this is what I want to set using a different 
     constructor

String streetName; //this is what I want to set using a different 
     constructor
 int roomMembers;


   ///getters and setters
    }

0 个答案:

没有答案