无法使用Moshi解析Json字符串

5

我正在尝试使用Moshi解析Json响应,但问题在于键的值是一个包装在字符串中的Json:

{"mobile_accounts_account_showProperties":"[{\"name\": \"current\"},{\"name\": \"available\"}]"}

这是我的课程

@Json(name = "mobile_accounts_account_showProperties")
private List<PropertyConfig> showProperties;

我尝试使用replace("\"[", "[")replace("\\", "")替换掉(" "),然后再解析,但这不是一个好的选择,因为这会移除其他我需要的引号。我尝试使用JsonAdapter但无法使其工作。JsonAdapter没有被调用。

public class PropertyConfigJsonAdapter {

public PropertyConfigJsonAdapter() {
}

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

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

    return new ArrayList<>();
}

我尝试这样做来查看JsonAdapter是否被调用,但它从未调用"fromJson"方法。以下是我调用适配器的方式:

MoshiConverterFactory.create(new Moshi.Builder().add(new PropertyConfigJsonAdapter()).build())
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接