GSON整数到特定字段的布尔值

Eli*_*zer 12 java json gson

我正在处理一个API,它返回整数(1 = true,other = false)来表示布尔值.

我已经看到了这个问题和答案,但我需要能够指定应该应用哪个字段,因为有时整数实际上是一个整数.

编辑:传入的JSON可能看起来像这样(也可能是String而不是int等...):

{ 
    "regular_int": 1234, 
    "int_that_should_be_a_boolean": 1
}
Run Code Online (Sandbox Code Playgroud)

我需要一种方法来指定int_that_should_be_a_boolean应该解析为布尔值,并regular_int应解析为整数.

Mah*_*ade 25

我们将为Gson提供一个小钩子,一个用于布尔值的自定义解串器,即一个实现JsonDeserializer<Boolean>接口的类:

CustomBooleanTypeAdapter

import java.lang.reflect.Type;
import com.google.gson.*;
class BooleanTypeAdapter implements JsonDeserializer<Boolean>
{
      public Boolean deserialize(JsonElement json, Type typeOfT, 
             JsonDeserializationContext context) throws JsonParseException
      {
          int code = json.getAsInt();
          return code == 0 ? false :
                   code == 1 ? true :
                 null;
      }
}
Run Code Online (Sandbox Code Playgroud)

要使用它,我们需要改变一点我们获取Gsonmapper实例的方式,使用工厂对象GsonBuilder,这是一种常用的模式方法GSON.

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
Gson gson = builder.create();
Run Code Online (Sandbox Code Playgroud)

对于原始类型使用低于一

 GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
    Gson gson = builder.create();
Run Code Online (Sandbox Code Playgroud)

享受JSON解析!

  • @Maheshwar Ligade那么问题**具体领域**部分呢?这个解决方案不适用于包含正常整数值的响应,例如`quantity:0`这个键不能表示为`Boolean` (3认同)
  • 如果我的json中有一个普通的布尔字段和整数值表示的字段,它是如何工作的? (2认同)
  • 这里的技巧是Java类中的参数类型确定要使用的适配器。因此,如果`quantity`是`int`,它将使用标准整数适配器。如果“ quantity”是“ boolean”,它将使用自定义的布尔适配器(将从0或1中提取值)。 (2认同)