亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

GSON 將特定字段的整數值動態轉換為布爾值

GSON 將特定字段的整數值動態轉換為布爾值

精慕HU 2022-08-03 15:23:42
如何處理獲得相同名稱但不同類型的字段?我有時在同一請求中從API獲得整數值,有時從API獲取布爾值。我想知道當我得到這樣的Json時如何處理。我創建了類型適配器,但它不起作用我想過創建不同的POJO類。但這個問題不僅僅是針對一個請求。出于這個原因,我不喜歡創建POJO。順便說一句,我看到了類似的問題,但它不能解決我的問題。{  "name" : "john doe",  "isValid" : true }有時我得到int{  "name" : "john doe",  "isValid" : 1 }我在獲取整數時收到意外的 json 異常class XModel{    private boolean isValid;    ...    ...}我想為每個請求返回一個布爾值。有誰知道如何解決這個問題?編輯:我想通過類型適配器阻止實例關鍵字解決方案:@Micha ? Ziober的回應對我有用。class BooleanJsonDeserializer implements JsonDeserializer<Boolean> {    private final Set<String> TRUE_STRINGS = new HashSet<>(Arrays.asList("true", "1", "yes"));    @Override    public Boolean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {        System.out.println(json);        JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();        if (jsonPrimitive.isBoolean()) {            return jsonPrimitive.getAsBoolean();        } else if (jsonPrimitive.isNumber()) {            return jsonPrimitive.getAsNumber().intValue() == 1;        } else if (jsonPrimitive.isString()) {            return TRUE_STRINGS.contains(jsonPrimitive.getAsString().toLowerCase());        }        return false;    }}
查看完整描述

3 回答

?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

如果類不大,你可以編寫自定義的 deserialiser,如下所示,您可以在其中控制傳入的元素:XModel


import com.google.gson.Gson;

import com.google.gson.GsonBuilder;

import com.google.gson.JsonDeserializationContext;

import com.google.gson.JsonDeserializer;

import com.google.gson.JsonElement;

import com.google.gson.JsonObject;

import com.google.gson.JsonParseException;

import com.google.gson.JsonPrimitive;


import java.io.File;

import java.io.FileReader;

import java.lang.reflect.Type;

import java.util.Arrays;

import java.util.HashSet;

import java.util.Set;


public class GsonApp {


    public static void main(String[] args) throws Exception {

        File jsonFile = new File("./resource/test.json").getAbsoluteFile();


        Gson gson = new GsonBuilder()

                .registerTypeAdapter(XModel.class, new XModelJsonDeserializer())

                .create();


        System.out.println(gson.fromJson(new FileReader(jsonFile), XModel.class));

    }

}


class XModelJsonDeserializer implements JsonDeserializer<XModel> {


    private final Set<String> TRUE_STRINGS = new HashSet<>(Arrays.asList("true", "1", "yes"));


    @Override

    public XModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        XModel response = new XModel();

        JsonObject jsonResponse = (JsonObject) json;

        response.setName(jsonResponse.get("name").getAsString());

        // other fields


        JsonElement dataElement = jsonResponse.get("isValid");

        if (dataElement.isJsonNull()) {

            response.setValid(false);

        } else if (dataElement.isJsonPrimitive()) {

            JsonPrimitive jsonPrimitive = dataElement.getAsJsonPrimitive();

            if (jsonPrimitive.isBoolean()) {

                response.setValid(jsonPrimitive.getAsBoolean());

            } else if (jsonPrimitive.isNumber()) {

                response.setValid(jsonPrimitive.getAsNumber().intValue() == 1);

            } else if (jsonPrimitive.isString()) {

                response.setValid(TRUE_STRINGS.contains(jsonPrimitive.getAsString()));

            }

            System.out.println("Json data is primitive: " + dataElement.getAsString());

        } else if (dataElement.isJsonObject() || dataElement.isJsonArray()) {

            response.setValid(true); //?!?!

        }


        return response;

    }

}

對于以下有效負載:JSON


{

  "name" : "john doe",

  "isValid" : true

}

以上程序打?。?/p>


Json data is primitive: true

XModel{name='john doe', isValid=true}

對于有效負載:JSON


{

  "name" : "john doe",

  "isValid" : 1

}

指紋:


Json data is primitive: 1

XModel{name='john doe', isValid=true}

您的模型很清楚,因為所有工作都是在 deserialiser 級別完成的。


一個稍微精確的解決方案是僅序列化。假設該模型如下所示:primitive


class XModel {


    private String name;


    @JsonAdapter(value = BooleanJsonDeserializer.class)

    private boolean isValid;


    // getters, setters

}

我們的 deserialiser 如下所示:BooleanJsonDeserializer


class BooleanJsonDeserializer implements JsonDeserializer<Boolean> {


    private final Set<String> TRUE_STRINGS = new HashSet<>(Arrays.asList("true", "1", "yes"));


    @Override

    public Boolean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        System.out.println(json);

        JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();

        if (jsonPrimitive.isBoolean()) {

            return jsonPrimitive.getAsBoolean();

        } else if (jsonPrimitive.isNumber()) {

            return jsonPrimitive.getAsNumber().intValue() == 1;

        } else if (jsonPrimitive.isString()) {

            return TRUE_STRINGS.contains(jsonPrimitive.getAsString().toLowerCase());

        }


        return false;

    }

}

您只需要在模型中使用此適配器注釋每個屬性,它就可以處理:,,等。boolean1True


查看完整回答
反對 回復 2022-08-03
?
弒天下

TA貢獻1818條經驗 獲得超8個贊

我不相信執行此映射很容易,但以下內容可能會有所幫助。


public void setIsValid(Object isValid) {

    String isValidString = String.valueOf(isValid).replace("0", "false").replace("1", "true");

    return Boolean.valueOf(isValidString);

}


查看完整回答
反對 回復 2022-08-03
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

你可以從Apache Commons Lang看一看。有一種方法可以將不同類型的字符串(和其他對象)解析為布爾值。BooleanUtilities


System.out.println(BooleanUtils.toBoolean(1));

System.out.println(BooleanUtils.toBoolean(true));

System.out.println(BooleanUtils.toBoolean("TrUe"));

System.out.println(BooleanUtils.toBoolean("true"));

輸出


true

true

true

true

但是,您可以像這樣組合它:BooleanUtils.toBoolean("1");false


String isValid = jsonPrimitive.get("isValid").getAsString();

System.out.println(BooleanUtils.toBoolean(isValid) || isValid.equals("1"));


查看完整回答
反對 回復 2022-08-03
  • 3 回答
  • 0 關注
  • 201 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號