使用GSON解析JSON时使用Enums [英] Using Enums while parsing JSON with GSON

查看:138
本文介绍了使用GSON解析JSON时使用Enums的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与我在前面提到的前一个问题有关



我试图解析相同的JSON,但现在我已经改变了我的类

  {
lower:20,
upper:40,
delimiter:,
scope:[$ {title}]
}

我的课目前看起来像:

  public class TruncateElement {

私人int较低;
private int upper;
私人字符串分隔符;
私人列表< AttributeScope>范围;
$ b // getters and setters


$ b public enum AttributeScope {

TITLE($ {title} ),
描述($ {description}),

private String scope;

AttributeScope(字符串范围){
this.scope = scope;
}

public String getScope(){
return this.scope;


code $


这段代码抛出一个异常,

  com.google.gson.JsonParseException:如果给定类型com.amazon.seo,JsonDeserializer EnumTypeAdapter无法反序列化json对象$ {title} .attribute.template.parse.data.AttributeScope 
at

这个例外是可以理解的,因为根据我之前提到的问题的解决方案,GSON期望Enum对象实际上被创建为

  $ {title}( $ {title}),
$ {description}($ {description});

但是由于这在语法上是不可能的,所以推荐的解决方案是什么? $ b

解决方案

From Gson的文档


Gson提供默认序列化并为Enums反序列化...如果您希望更改默认表示形式,您可以通过GsonBuilder.registerTypeAdapter(Type,Object)注册类型适配器来完成。


以下是一种这样的方法。

  import java.io.FileReader; 
import java.lang.reflect.Type;
import java.util.List;

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.JsonParseException;

public class GsonFoo
{
public static void main(String [] args)throws Exception
{
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(AttributeScope.class,new AttributeScopeDeserializer());
Gson gson = gsonBuilder.create();

TruncateElement element = gson.fromJson(new FileReader(input.json),TruncateElement.class);

System.out.println(element.lower);
System.out.println(element.upper);
System.out.println(element.delimiter);
System.out.println(element.scope.get(0));
}
}

类AttributeScopeDeserializer实现了JsonDeserializer< AttributeScope>
{
@Override
public AttributeScope反序列化(JsonElement json,类型typeOfT,JsonDeserializationContext上下文)
抛出JsonParseException
{
AttributeScope [] scopes = AttributeScope。值();
for(AttributeScope scope:scopes)
{
if(scope.scope.equals(json.getAsString()))
return scope;
}
返回null;
}
}

class TruncateElement
{
int lower;
int上;
字符串分隔符;
列表< AttributeScope>范围;


enum AttributeScope
{
TITLE($ {title}),DESCRIPTION($ {description});

字符串范围;

AttributeScope(字符串范围)
{
this.scope = scope;
}
}


This is related to a previous question that I asked here earlier

JSON parsing using Gson

I am trying to parse the same JSON, but now I have changed my classes a little bit.

{
    "lower": 20,
    "upper": 40,
    "delimiter": " ",
    "scope": ["${title}"]
}

My class now looks like:

public class TruncateElement {

   private int lower;
   private int upper;
   private String delimiter;
   private List<AttributeScope> scope;

   // getters and setters
}


public enum AttributeScope {

    TITLE("${title}"),
    DESCRIPTION("${description}"),

    private String scope;

    AttributeScope(String scope) {
        this.scope = scope;
    }

    public String getScope() {
        return this.scope;
    }
}

This code throws an exception,

com.google.gson.JsonParseException: The JsonDeserializer EnumTypeAdapter failed to deserialized json object "${title}" given the type class com.amazon.seo.attribute.template.parse.data.AttributeScope
at 

The exception is understandable, because as per the solution to my previous question, GSON is expecting the Enum objects to be actually be created as

${title}("${title}"),
${description}("${description}");

But since this is syntactically impossible, what are the recommended solutions, workarounds?

解决方案

From the documentation for Gson:

Gson provides default serialization and deserialization for Enums... If you would prefer to change the default representation, you can do so by registering a type adapter through GsonBuilder.registerTypeAdapter(Type, Object).

Following is one such approach.

import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.List;

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.JsonParseException;

public class GsonFoo
{
  public static void main(String[] args) throws Exception
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(AttributeScope.class, new AttributeScopeDeserializer());
    Gson gson = gsonBuilder.create();

    TruncateElement element = gson.fromJson(new FileReader("input.json"), TruncateElement.class);

    System.out.println(element.lower);
    System.out.println(element.upper);
    System.out.println(element.delimiter);
    System.out.println(element.scope.get(0));
  }
}

class AttributeScopeDeserializer implements JsonDeserializer<AttributeScope>
{
  @Override
  public AttributeScope deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException
  {
    AttributeScope[] scopes = AttributeScope.values();
    for (AttributeScope scope : scopes)
    {
      if (scope.scope.equals(json.getAsString()))
        return scope;
    }
    return null;
  }
}

class TruncateElement
{
  int lower;
  int upper;
  String delimiter;
  List<AttributeScope> scope;
}

enum AttributeScope
{
  TITLE("${title}"), DESCRIPTION("${description}");

  String scope;

  AttributeScope(String scope)
  {
    this.scope = scope;
  }
}

这篇关于使用GSON解析JSON时使用Enums的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆