简体   繁体   English

使用gson将枚举作为单例转换为JSON

[英]convert enum as singleton to JSON using gson

I have singleton implementation of enum as below : 我有枚举的单例实现,如下所示:

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;
    }
}

I want to convert this DeviceDetail to JSON using GSON, for that I have written 我想使用GSON将此DeviceDetail转换为JSON,因为我已经写了

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

I am calling this method as 我称这种方法为

convertObjectToJsonString(DeviceDetail.INSTANCE)

but it only returns me the string "INSTANCE" not key value pairs as it does for objects. 但它只返回字符串“ INSTANCE”而不是键值对,就像对对象一样。 Suggest the changes need to be made so that I get string with all fields in enum in key value JSON. 建议需要进行更改,以便在键值JSON中获取枚举中所有字段的字符串。

I have ended up in using a not so elegant workaround as below : 我最终使用了一种不太优雅的解决方法,如下所示:

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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM