java - 具有多个已知类的 GSON

标签 java json gson

我有以下 json

{ "file": {"file": "foo.c", "owner": "user123"}
  "methods": [{"name": "proc1", "value":"val"}, {"name":"proc2","value":"val2"}]
  etc...
}

我知道我可以做类似的事情

class file{
      public String file
      public String owner
    }
class methods{
      public String name
      public String value
    }

我可以打电话

File file= gson.fromJson(jsonInString, File.class);  
methods[] array = gson.fromJson(jsonInString, methods[].class);

但是如果我需要处理一个包含许多对象的复杂 json,我该怎么办 我无法指定 gson.fromJson(jsonInString, ListOfClasses)

最佳答案

我通常按照这种方法将任何复杂的类从 json 转换为对象。这种方法适用于几乎所有东西,如列表、 map 等。这个想法很简单,为复杂的类创建持有者,然后创建类。提供尽可能多的深度。诀窍是匹配 Json 中的名称和您的持有者(和子类)。

文件配置:

class FileConfig{
  public String file;
  public String owner;

  //define toString, getters and setters 
}

方法类:

class Method{
  public String name;
  public String value;

  //define toString, getters and setters   
}

方法配置:

class MethodConfig{
  List<Method> methods = null;

  //define toString, getters and setters 
}

持有配置:

public class HolderConfig {

  private FileConfig file = null;
  private MethodConfig methods = null;

  public FileConfig getFile() {
    return file;
  }

  public void setFile(FileConfig file) {
    this.file = file;
  }
  public MethodConfig getMethods() {
    return file;
  }

  public void setMethods(MethodConfig methods) {
    this.methods = methods;
  } 
}

构建配置:

public class HolderConfigBuilder {

public static HolderConfig build(JsonObject holderConfigJson) {

    HolderConfig configHolderInstance = null;         

    Gson gsonInstance = null;

    gsonInstance = new GsonBuilder().create();

    configHolderInstance = gsonInstance.fromJson(holderConfigJson,HolderConfig.class);

    return configHolderInstance;
  }
}

演示类:

public class App 
{
      public static void main( String[] args )
      {

           HolderConfig configHolderInstance = null;
           FileConfig file = null;
           configHolderInstance = HolderConfigBuilder.build(<Input Json>);
           file = configHolderInstance.getFile();
           System.out.println("The fileConfig is : "+file.toString());
      }
 }

输入Json:

{ "file": {"file": "foo.c", "owner": "user123"}
  "methods": [
               {"name": "proc1", "value":"val"},
               {"name":"proc2","value":"val2"}
             ]
}

注意:在您的测试代码中编写代码以获取输入 JSON。

通过这种方式,无论何时向 JSON 添加更多元素,都必须为该元素创建一个单独的类,并将与 json 中相同的元素名称添加到 HolderConfig 中。您无需更改其余代码。

希望对您有所帮助。

关于java - 具有多个已知类的 GSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38226024/

相关文章:

javascript - 递归操作javascript对象数据结束

java - 使用Gson解析不同字段的子类

android - com.google.gson.JsonParseException : Failed parsing JSON source: java. io.BufferedReader 到 Json - 对这个问题感到困惑

java - 使用 GSON 从对象转换为字符串时添加了不需要的字符

java - 具有相同路径的 JAX-RS 多个类

Java Singleton 有时会抛出 NullPointerException

java - HashSet<POJO>.contains 不当行为

java - Android,在tomcat服务器上传一个文件

php - 用jquery返回json数据?

javascript - 很难将 json 字符串从服务器转换为数组