如果我对我的解释不是很清楚,我会道歉但是如果要求,我会添加并编辑这个问题.
我正在开发一个Android应用程序,它通过外部API接收数据,并使用ORMLite在本地存储数据.在本地存储数据并使用ORMLite之前,我有一些模型从服务器检索JSON并通过以下方式对其进行解析:
Gson gson = new Gson();
String result = ApiClient.httpPost("/user_route");
User user = gson.fromJson(result, User.class);
Run Code Online (Sandbox Code Playgroud)
User类已定义
public class User {
int id;
String name;
ArrayList<Image> media;
}
Run Code Online (Sandbox Code Playgroud)
而Image类:
public class Image {
int id;
int creator_id;
String url;
}
Run Code Online (Sandbox Code Playgroud)
这是模型和方法的简化表示,但我相信我保留了所有相关信息.BTW,media是一个包含的JSON对象Images.
现在我还试图在本地存储数据.为了使用ORMLite在Users和Images之间建立关系,你似乎必须使用ForeignCollection类和@ForeignCollectionField注释.我不相信Gson可以直接media将User类中的字段作为ForeignCollection对象解析,所以我认为我需要创建两个字段mediaCollection和media.
使用ORMLite,User类现在看起来像这样:
@DatabaseTable(tableName = "Users")
public class User {
@DatabaseField(generatedId = true)
int id;
@DatabaseField
String name;
@ForeignCollectionField
ForeignCollection<Image> mediaCollection;
ArrayList<Image> media;
}
Run Code Online (Sandbox Code Playgroud)
带有ORMLite的Image类如下所示:
@DatabaseTable(tableName = "Images")
public class …Run Code Online (Sandbox Code Playgroud) 我正在使用 jackson 库将 JSON 映射到对象。我已经将问题简化了很多,这就是发生的情况:
public class MyObject{
public ForeignCollection<MySecondObject> getA(){
return null;
}
public ForeignCollection<MyThirdObject> getB(){
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在解析一个空的 JSON 字符串:
ObjectMapper mapper = new ObjectMapper();
mapper.readValue("{}", MyObject.class);
Run Code Online (Sandbox Code Playgroud)
在 上readValue,我得到这个异常:
com.fasterxml.jackson.databind.JsonMappingException: Can not find a deserializer for non-concrete Collection type [collection type; class com.j256.ormlite.dao.ForeignCollection, contains [simple type, class com.test.MyThirdObject]]
Run Code Online (Sandbox Code Playgroud)
当我在类中有两个 返回. 删除其中一种方法不会导致任何异常。getMyObjectForeignCollectionget
实际上,我对映射器查看get方法这一事实感到惊讶,它应该只设置我指示的字段。
这里发生了什么?