使用Gson解析一个嵌套的动态模块



我有一个JSON,看起来差不多是这样的:

{
"modules": {
"someExistingModule": {
"name": "pug",
...
},
"randomExistingModule": {
"type": "cat",
...
},
"myNewModule": {   // <----- I care about this module. Note that this is NOT an array
"modules": {
"img1": {
"type": "image",
"url": "https://some/random/image,
"altText": "Some image description
},
"img2": {
"type": "image",
"url": "https://some/random/image,
"altText": "Some image description
},
"img3": {
"type": "image",
"url": "https://some/random/image,
"altText": "Some image description
},
"txt1": {           // <------ Updated JSON
"type": "text",
"content": "Hello world 1"
},
"txt2": {
"type": "text",
"content": "Hello world 2"
},
...
}
}

myModule内部可以有N个数的imgN对象和txtN对象。我需要动态解析这个

我当前的Response类是这样的:

public class MyModuleResponse extends SomeResponseClass
{
@Override
public void parse(InputStream data)
{
T responseBody = readJsonStream(data, MyModuleResponseBody.class());
MyModuleDataParser.parse(responseBody);
}

MyModuleDataParser.java

...
public static MyModuleDataParser parse(@Nullable MyModuleResponseBody body)
{
parseSomeExistingModule();
parseRandomExistingModule();
parseMyNewModule(); // <--- This is the new module I'm trying to parse. Currently, this method is empty.
}

MyModuleResponseBody.java

public class MyModuleResponseBody
{
public Modules modules;
public static class Modules
{
SomeExistingModule someExistingModule;
RandomExistingModule randomExistingModule;
MyNewModule myNewModule; // <----- My new module
}
public static class SomeExistingModule
{
String name;
...
}
public static class RandomExistingModule
{
String type;
...
}
public static class MyNewModule
{
public ??? modules;   // <--- Trying to define the Type here. Something like List<MyImageModule>. But, it won't work
}

MyImageModule.java

public class MyImageModule extends Module // <---- Update: This class now extends a generic Module class
{
private String url;
private String altText;
}

MyTextModule.java<----新模块

public class MyTextModule extends Module    // New class
{
private String content;
}

Module.java

public class Module  // <----- New parent class
{
protected String type;
}

如何从myNewModule创建MyImageModule的列表?我相信我需要使用某种TypeAdapter从Gson库。但是,我不熟悉如何在现有的响应中做到这一点。

使用Map<String, MyImageModule>,实际上是一个hashmap来解决json中non-list modules对象的问题。

public static class MyNewModule {
public Map<String, MyImageModule> modules; // initialize as a hashmap
}

最新更新