【发布时间】:2023-03-08 07:02:01
【问题描述】:
我在使用 Gson 将 JSON 字符串转换为对象数组时遇到问题。我已经尝试了我能找到的一切,但没有任何帮助。 我的代码是:
public static ProizvodiViewModel GetProizvode(String tip) {
String strJson = HttpManager.simpleResponseGet("http://192.168.0.15:21951/api/Proizvodi/SearchProizvodiByVrsta", tip);
Gson gson = new Gson();
ProizvodiViewModel x = new ProizvodiViewModel();
x.Proizvodi = new ProizvodViewModel[]{};//tried also with this line commented
try {
//1st attempt
//x.Proizvodi = gson.fromJson(strJson, ProizvodViewModel[].class);
//2nd
//Type type = new TypeToken<List<ProizvodViewModel[]>>() {}.getType();
//x.Proizvodi = gson.fromJson(strJson, type);
//3rd and so forth (cause many of answers here on SO had almost same idea)
Type collectionType = new TypeToken<Collection<ProizvodViewModel>>() {}.getType();
Collection<ProizvodViewModel> enums = gson.fromJson(strJson, collectionType);
} catch (Exception e) {
System.out.println("ERROR IN GSON");
System.out.println(e.getMessage());
}
return x;
}
我放了 try catch 否则应用程序会崩溃,而且我无法读取 println 的内容。
还有我的课:
public class ProizvodViewModel {
public int Id ;
public boolean IsDeleted ;
public String Naziv ;
public float Cijena ;
public byte[] Slika ;
public byte[] SlikaThumb ;
public String Status ;
public int ProizvodDetaljiId ;
public int VrstaId ;
}
public class ProizvodiViewModel
{
public ProizvodViewModel[] Proizvodi;
}
我以 JSON 格式获取数据,您可以在此处看到:http://pastebin.com/6C7936Uq 我正在使用 Android Studio 1.1.0 和 api 16。
编辑:发布已解决的问题。我让我的 api 返回包含 2 个字节数组属性的 json 字符串,这些属性被转换(我不知道如何)为 base64 字符串,我试图将它们映射到字节数组中,这导致了错误。 我用asp写了我的api。 net 应用程序,所以如果有人想进一步解释为什么会发生这种情况,请这样做。
【问题讨论】:
标签: java android android-studio gson