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

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

本文介绍了GSON整数到特定字段的布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我见过,但我需要能够指定应该应用哪个字段,因为有时整数实际上是整数。



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

  {
regular_int:1234,
int_that_should_be_a_boolean:1
}

我需要一种方法来指定应将 int_that_should_be_a_boolean 解析为布尔值,并且应将 regular_int 解析为一个整数。

解决方案

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

  import java.lang.reflect.Type; 
import com.google.gson。*;
类BooleanTypeAdapter实现JsonDeserializer< Boolean>
{
public Boolean deserialize(JsonElement json,Type typeOfT,
JsonDeserializationContext context)throws JsonParseException
{
int code = json.getAsInt();
返回码== 0? false:
code == 1? true:
null;


$ / code>

要使用它,我们需要稍微改变一下我们使用工厂对象GsonBuilder获取 Gson 映射器实例的方式,GsonBuilder是使用 GSON 的常用模式方法。

  GsonBuilder builder = new GsonBuilder(); 
builder.registerTypeAdapter(Boolean.class,new BooleanTypeAdapter());
Gson gson = builder.create();

对于原始类型使用低于1

  GsonBuilder builder = new GsonBuilder(); 
builder.registerTypeAdapter(boolean.class,new BooleanTypeAdapter());
Gson gson = builder.create();

享受 JSON 解析!


I'm dealing with an API that sends back integers (1=true, other=false) to represent booleans.

I've seen this question and answer, but I need to be able to specify which field this should apply to, since some times an integer is actually an integer.

EDIT: The incoming JSON could possibly look like this (could also be String instead of int, etc...):

{
    "regular_int": 1234,
    "int_that_should_be_a_boolean": 1
}

I need a way to specify that int_that_should_be_a_boolean should be parsed as a boolean and regular_int should be parsed as an integer.

解决方案

We will provide Gson with a little hook, a custom deserializer for booleans, i.e. a class that implements the JsonDeserializer<Boolean> interface:

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

To use it we’ll need to change a little the way we get the Gson mapper instance, using a factory object, the GsonBuilder, a common pattern way to use GSON is here.

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter());
Gson gson = builder.create();

For primitive Type use below one

 GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
    Gson gson = builder.create();

Enjoy the JSON parsing!

这篇关于GSON整数到特定字段的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:33