Android json/gson反序列化
我正在尝试解析从 php 文件收到的以下 json 数组:
actionsArray = [["19.431","19.438"],[["8","107"],[]],["u1", "u2"]]
我主要对访问数组 [["8","107"],[]]; 感兴趣但是,我收到错误“com.google.gson.JsonParseException:期望数组但找到对象:名称:null Grams:null 0 操作:null
这是我的代码摘录:
用户类包含:字符串名称;int []操作字符串克;
JSONArray inputarray;
try {
int[] userActionsArray = new int[0];
inputarray = new JSONArray(br.readLine());
JSONArray gramsArray = (JSONArray)inputarray.get(0);
JSONArray actionsArray = (JSONArray)inputarray.get(1);
JSONArray namesArray = (JSONArray) inputarray.get(2);
User[] values = new User[namesArray.length()];
Gson gson = new Gson();
*User userAction = gson.fromJson(inputarray.toString(), User.class);
//error occurs on the above line*
...
I am trying to parse the following json array that I receive from my php file:
actionsArray = [["19.431","19.438"],[["8","107"],[]],["u1","u2"]]
I'm primarily interested in accessing the array [["8","107"],[]]; however, I get the error, "com.google.gson.JsonParseException: Expecting array but found object: Name: null Grams: null 0 Actions: null
Here's an excerpt from my code:
User class contains: String name; int[] actions; String grams
JSONArray inputarray;
try {
int[] userActionsArray = new int[0];
inputarray = new JSONArray(br.readLine());
JSONArray gramsArray = (JSONArray)inputarray.get(0);
JSONArray actionsArray = (JSONArray)inputarray.get(1);
JSONArray namesArray = (JSONArray) inputarray.get(2);
User[] values = new User[namesArray.length()];
Gson gson = new Gson();
*User userAction = gson.fromJson(inputarray.toString(), User.class);
//error occurs on the above line*
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您尝试解析数组但服务作为对象响应时,通常会出现此问题。因此,首先测试您收到的响应,然后尝试进行相应的解析。
This problem occurs usually when you try to parse array but service is responding as object. So first test the response you are getting then try to parse accordingly.
JSONArray
来自 org.json,.toString() 方法将其返回为["first","second"]
(源可用 此处)您需要您的 JSON 如下所示:
{ myArray : [ "first" , “第二” ] }
让 Gson 解析它...您的 POJO(在您的情况下User.class
)应该如下所示:A
JSONArray
is from org.json, which the .toString() method returns as["first","second"]
(source available here)You need your JSON to look like:
{ myArray : [ "first", "second" ] }
for Gson to parse it... Where your POJO (in your caseUser.class
) should look like this: