无法用 Moshi 解析 Json 字符串

Eze*_*sto 5 moshi jsonparser

我正在尝试使用 Moshi 解析 Json 响应,我遇到的问题是键的值是字符串上的 Json 包装:

{"mobile_accounts_account_showProperties":"[{\"name\": \"current\"},{\"name\": \"available\"}]"}
Run Code Online (Sandbox Code Playgroud)

这是我的课

@Json(name = "mobile_accounts_account_showProperties")
private List<PropertyConfig> showProperties;
Run Code Online (Sandbox Code Playgroud)

我尝试在解析之前用 areplace("\"[", "[")和 a删除 ("")replace("\\", "")但不是一个选项,因为这删除了我确实需要的一些其他引号。我尝试使用 JsonAdapter 但我无法做到这一点。JsonAdapter 没有接到电话。

public class PropertyConfigJsonAdapter {

public PropertyConfigJsonAdapter() {
}

@ToJson
String toJson(List<PropertyConfig> card) {
    return "";
}

@FromJson
List<PropertyConfig> fromJson(String object) {

    return new ArrayList<>();
}
Run Code Online (Sandbox Code Playgroud)

我尝试这样做以查看 JsonAdapter 是否正在调用,但它从未调用过“fromJson”方法。这是我调用适配器的方式:

MoshiConverterFactory.create(new Moshi.Builder().add(new PropertyConfigJsonAdapter()).build())
Run Code Online (Sandbox Code Playgroud)

Eri*_*ran 1

最简单的方法是将值作为字符串读取并从那里对其进行解码。您可以使用 JsonAdapter 使其对应用程序代码透明,如下所示ShowPropertiesContainer.ADAPTER

public final class ShowPropertiesContainer {
  public final List<PropertyConfig> showProperties;

  public static final Object ADAPTER = new Object() {
    @FromJson public ShowPropertiesContainer fromJson(JsonReader reader,
        JsonAdapter<ShowPropertiesContainer> fooAdapter,
        JsonAdapter<List<PropertyConfig>> propertyConfigListAdapter) throws IOException {
      ShowPropertiesContainer showPropertiesContainer = fooAdapter.fromJson(reader);
      return new ShowPropertiesContainer(propertyConfigListAdapter.fromJson(
          showPropertiesContainer.mobile_accounts_account_showProperties),
          showPropertiesContainer.mobile_accounts_account_showProperties);
    }
  };

  final String mobile_accounts_account_showProperties;

  ShowPropertiesContainer(List<PropertyConfig> showProperties,
      String mobile_accounts_account_showProperties) {
    this.showProperties = showProperties;
    this.mobile_accounts_account_showProperties = mobile_accounts_account_showProperties;
  }
}

public final class PropertyConfig {
  public final String name;

  PropertyConfig(String name) {
    this.name = name;
  }
}

@Test public void showPropertiesContainer() throws IOException {
  Moshi moshi = new Moshi.Builder()
      .add(ShowPropertiesContainer.ADAPTER)
      .build();
  JsonAdapter<ShowPropertiesContainer> adapter = moshi.adapter(ShowPropertiesContainer.class);
  String encoded =
      "{\"mobile_accounts_account_showProperties\":\"[{\\\"name\\\": \\\"current\\\"},"
          + "{\\\"name\\\": \\\"available\\\"}]\"}";
  ShowPropertiesContainer showPropertiesContainer = adapter.fromJson(encoded);
}
Run Code Online (Sandbox Code Playgroud)