簡體   English   中英

如何使用GSON保留JSON對象中特定鍵的數據類型?

[英]How to preserve data types of a particular key in JSON Object using GSON?

我有我原來的JSON字符串,其中我有鍵和值,如下所示 -

{
  "u":{
     "string":"1235"
  },
  "p":"2047935",
  "client_id":{
     "string":"5"
  },
  "origin":null,
  "item_condition":null,
  "country_id":{
     "int":3
  },
  "timestamp":{
     "long":1417823759555
  },
  "impression_id":{
     "string":"2345HH*"
  },
  "is_consumerid":true,
  "is_pid":false
}

例如,一個鍵是"u" ,其值為 -

{
    "string":"1235"
}

同樣,另一個關鍵是"country_id" ,其值為 -

{
    "int":3
}

現在我需要做的是,我需要代表鍵值對,如下所示。 如果任何值是字符串數據類型(如鍵u的值),則用雙引號表示它的值,否則不用雙引號表示它的值。 country_id的含義值不在String雙引號中,因為它是一個int。

"u": "1235"
"p": "2047935"
"client_id": "5"
"origin":null
"item_condition":null
"country_id": 3 // I don't have double quotes here around 3 since country_id was int that's why
"timestamp": 1417823759555
"impression_id": "2345HH*"
"is_consumerid": true
"is_pid": false

然后我需要制作另一個看起來像這樣的json字符串 -

{
    "u": "1235",
    "p": "2047935",
    "client_id": "5",
    "origin":null,
    "item_condition":null,
    "country_id": 3,
    "timestamp": 1417823759555,
    "impression_id": "2345HH*",
    "is_consumerid": true,
    "is_pid": false
}

所以我開始這樣的方法並帶有以下代碼 -

    String response = "original_json_string";
    Type type = new TypeToken<Map<String, Object>>() {}.getType();

    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();

    for (Map.Entry<String, JsonElement> object : jsonObject.entrySet()) {
        if (object.getValue() instanceof JsonObject) {
            String data = object.getValue().toString();
            Map<String, Object> jsonIn = gson.fromJson(data, type);
            Map<String, Object> jsonOut = new HashMap<String, Object>();

            Set<String> keys = jsonIn.keySet();
            for (String key : keys) {
                Object value = jsonIn.get(key);
                if (value instanceof Map) {
                    Map<?, ?> mapValue = (Map<?, ?>) value;
                    for (Map.Entry<?, ?> entry : mapValue.entrySet()) {
                        jsonOut.put(key, entry.getValue());
                    }
                } else {
                    jsonOut.put(key, value);
                }
            }

            // System.out.println(jsonOut);

            String json = gson.toJson(jsonOut);
            System.out.println(json);

        }
    }

上面的代碼工作正常。 只有不起作用的是 - 當我嘗試將jsonOut映射序列化為JSON時,某些鍵值無法正確顯示。 例如country_idtimestamp這兩個鍵值是錯誤的。

所以現在我的json打印得像這樣 - 你可以看到, country_id值是3.0而不應該是3.類似的timestamp值是1.417823759555E12而應該是1417823759555

{
    "u": "1235",
    "p": "2047935",
    "client_id": "5",
    "origin":null,
    "item_condition":null,
    "country_id": 3.0,              // this is different value
    "timestamp": 1.417823759555E12, // and this is different value
    "impression_id": "2345HH*",
    "is_consumerid": true,
    "is_pid": false
}

所以新的json應該像這樣打印出來 -

{
    "u": "1235",
    "p": "2047935",
    "client_id": "5",
    "origin":null,
    "item_condition":null,
    "country_id": 3,
    "timestamp": 1417823759555,
    "impression_id": "2345HH*",
    "is_consumerid": true,
    "is_pid": false
}

我怎么能這樣做,我做錯了什么?

默認情況下,Gson使用Double來映射任何JSON編號。 既然你沒有明確說明Java映射(即你已經使用過Object

Type type = new TypeToken<Map<String, Object>>() {}.getType();

Gson將使用其默認值。

除非你指定了確切的類型,因為你的JSON似乎是動態的,因此你需要自己進行轉換,然后再將它添加到最終的序列化集合中。

輕微重寫:

        for (String key : keys) {
            Object value = jsonIn.get(key);
            if (value instanceof Map) {
                Map<?, ?> mapValue = (Map<?, ?>) value;
                for (Map.Entry<?, ?> entry : mapValue.entrySet()) {
                    Double oldValue = (Double) entry.getValue();
                    Object newValue;
                    switch(entry.getKey()) {
                        case "int":
                            newValue = Integer.valueOf(oldValue.intValue());
                            break;
                        case "long":
                            newValue = Long.valueOf(oldValue.longValue());
                            break;
                        case "string":
                            newValue = oldValue;
                            break;
                        default:
                            newValue = "Error -- could not translate";
                    }
                    jsonOut.put(key, newValue);
                }
            } else {
                jsonOut.put(key, value);
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM