使用具有相同变量的varing数据类型序列化JSON

时间:2016-07-11 11:10:16

标签: java json jackson

我正在尝试使用Opensignal API,并且在尝试使用Jackson 2.0序列化结果时遇到了问题。 networkRank可以是数组,也可以是字符串

我如何设置Jackson以正确序列化JSON,就好像它是一个字符串一样,将其保存到此String networkRank属性,否则将其保存到List <NetworkRank> = new ArrayList<NetworkRank>()

这些是他们的api的结果:(查看下面的networkRank)

{
    "apiVersion": "2",
    "latitude": "14.55669",
    "longitude": "121.370119",
    "distance": "10",
    "network_type": "10",
    "perMinuteCurrent": 0,
    "perMinuteLimit": 10,
    "perMonthCurrent": 7,
    "perMonthLimit": 2000,
    "networkRank": "No results for this area"   
}

{
    "apiVersion": "2",
    "latitude": "14.55669",
    "longitude": "121.370119",
    "distance": "10",
    "network_type": "10",
    "perMinuteCurrent": 0,
    "perMinuteLimit": 10,
    "perMonthCurrent": 7,
    "perMonthLimit": 2000,
    "networkRank": [
         {
         "networkName": "T-Mobile",
         "networkId": "310260",
  "type3G": {
    "networkName": "T-Mobile",
    "networkId": "310260",
    "networkType": "3",
    "averageRssiAsu": "10.934899",
    "averageRssiDb": "-91.130203",
    "sampleSizeRSSI": "437532",
    "downloadSpeed": "4532.8305",
    "uploadSpeed": "1124.9649",
    "pingTime": "148.8205",
    "reliability": "94.5944170771741"
  },
  "type4G": {
    "networkName": "EE",
    "networkId": "23430",
    "networkType": "4",
    "averageRsrpAsu": "33.865632",
    "averageRsrpDb": "-106.134368",
    "sampleSizeRSRP": "284041",
    "downloadSpeed": "9851.1000",
    "uploadSpeed": "4377.3200",
    "pingTime": "87.0000",
    "reliability": "96.2113095238094"
     }
   }
  ]  
}

1 个答案:

答案 0 :(得分:3)

对json字符串或数组使用相同字段的最简单方法可能是使用Object字段。此解决方案不需要自定义序列化程序和反序列化程序。以下是Jackson注释的示例类:

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class NetworkStatistics {

    private String apiVersion;
    private String latitude;
    private String longitude;
    private String distance;
    @JsonProperty("network_type")
    private String networkType;
    private int perMinuteCurrent;
    private int perMinuteLimit;
    private int perMonthCurrent;
    private int perMonthLimit;
    private Object networkRank;

    public NetworkStatistics() {
    }

    // getters
}

以下是将api响应的json字符串反序列化为NetworkStatistics实例的示例:

ObjectMapper mapper = new ObjectMapper();
NetworkStatistics networkStatistics = mapper.readValue(json, NetworkStatistics.class);

以及将NetworkStatistics实例序列化为json String的示例:

String json = mapper.writeValueAsString(networkStatistics))

如果json中的networkRank是字符串值,则反序列化后的实例字段将是String字段。如果它是json数组,则实例字段将是java.util.ArrayList字段。

希望这可以提供帮助。