使用gson将enum作为singleton转换为JSON

时间:2016-01-12 06:44:08

标签: java enums singleton android gson

我有以下单例实现的枚举:

public enum DeviceDetail{

    INSTANCE;  
    private  Context context = null;
    private  int handlercheck = 0;
    private  String network = "";
    private  String deviceInfo = "NoData";
    private  String androidVersion = "";
    private  String appVersion = "";
    private  String appName = "";
    private  String deviceID;
    private  String deviceinfo;

    public void initilize(){
           // deviceInfo = getDeviceInfo();
            networktype = getNetworktype(context);
            deviceID = getDeviceID(context);
            //androidVersion = getAndroidVersion();
            appVersion = getAppVersion(context);
            appName = getAppName(context);
    }    
    DeviceDetail(){
        deviceInfo = getDeviceInfo();
        androidVersion = getAndroidVersion();
        initilize();

    }

    public static DeviceDetail getInstance() {
        return DeviceDetail.INSTANCE;
    }
}

我想使用GSON将此DeviceDetail转换为JSON,因为我已经编写了

public static String convertObjectToJsonString(DeviceDetail deviceData)    {
        Gson gson = new Gson();
        return gson.toJson(deviceData);
    }

我将此方法称为

convertObjectToJsonString(DeviceDetail.INSTANCE)

但它只返回字符串“INSTANCE”而非键值对,就像对象一样。建议需要进行更改,以便在键值JSON中获取enum中所有字段的字符串。

1 个答案:

答案 0 :(得分:0)

我最终使用了一个不太优雅的解决方法,如下所示:

public static String convertObjectToJsonString(DeviceDetail deviceData) {
        // Gson gson = new Gson();
        // GsonBuilder gb = new GsonBuilder();
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("androidVersion", deviceData.getAndroidVersion());
        jsonObject.addProperty("appName", deviceData.getAppName());
        jsonObject.addProperty("appVersion", deviceData.getAppVersion());
        jsonObject.addProperty("networkType", deviceData.getNetworktype());
        jsonObject.addProperty("deviceInfo", deviceData.getDeviceInfo());
        jsonObject.addProperty("deviceID", deviceData.getDeviceID());
        jsonObject.addProperty("city", deviceData.getCity());
        jsonObject.addProperty("country", deviceData.getCountry());
        //jsonObject.addProperty("appName",deviceData.getAppName());

        return jsonObject.toString();
    }