Android 使用 gson 解析 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21503158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse JSON object with gson
提问by onCreate
I'm trying to parse JSON like:
我正在尝试解析 JSON,如:
{"response":[123123, 1231231, 123124, 124124, 111111, 12314]}
With GSON, making
使用 GSON,使
Gson gson = new GsonBuilder().create();
int[] friends = new Gson().fromJson(answer, int[].class);
System.out.print(friends[0]);
But get Error Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
但是得到 Error Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
How to parse this numbers in array?
如何解析数组中的这些数字?
回答by Josh Feldman
You're going to want to create a model class first that GSON can bind your json to:
您首先要创建一个模型类,GSON 可以将您的 json 绑定到:
public class ResponseModel {
private List<Integer> response = new ArrayList<Integer>();
public List<Integer> getResponse() {
return response;
}
@Override
public String toString() {
return "ResponseModel [response=" + response + "]";
}
}
Then you can call
然后你可以打电话
Gson gson = new Gson();
ResponseModel responseModel = gson.fromJson("{\"response\":[123123, 1231231, 123124, 124124, 111111, 12314]}",
ResponseModel.class);
List <Integer> responses = responseModel.getResponse();
// ... do something with the int list
回答by Brian Roach
The other option you have outside of using a wrapper class is simply to get the array from the parse tree.
除了使用包装器类之外,您还可以选择从解析树中获取数组。
Use the JsonParser
to create the tree, get your array from it, then convert to int[]
using Gson
:
使用JsonParser
来创建树,从中获取数组,然后转换为int[]
使用Gson
:
public class App
{
public static void main( String[] args ) throws IOException
{
String json = "{\"response\":[1,2,3,4,5]}";
JsonObject jo = new JsonParser().parse(json).getAsJsonObject();
JsonArray jsonArray = jo.getAsJsonArray("response");
int[] myArray = new Gson().fromJson(jsonArray, int[].class);
System.out.println(Arrays.toString(myArray));
}
}
Note that you could also just work with the JsonArray
directly and not convert it to an int[]
depending on your use case.
请注意,您也可以JsonArray
直接使用 ,而不是int[]
根据您的用例将其转换为。
System.out.println(jsonArray.get(0).getAsInt());
回答by Elshan
Try this method
试试这个方法
String json1 = "[{\"contactName\":\"3\",\"contactNumber\":\"3\"},{\"contactName\":\"4\",\"contactNumber\":\"4\"}]";
JsonElement json = new JsonParser().parse(json1);
JsonArray array= json.getAsJsonArray();
Iterator iterator = array.iterator();
List<ContactDetail> details = new ArrayList<ContactDetail>();
while(iterator.hasNext()){
JsonElement json2 = (JsonElement)iterator.next();
Gson gson = new Gson();
ContactDetail contact = gson.fromJson(json2, ContactDetail.class);
//can set some values in contact, if required
details.add(contact);
}
I got another form here
我在这里得到了另一种形式
回答by Sukitha Udugamasooriya
A Kotlin soulution
Kotlin 解决方案
val myResponse = Gson().fromJson(responseStr, MyResponse::class.java)
回答by Devrim
Json value has an object as response which holds an integer array. You have to define its class correctly first:
Json 值有一个对象作为响应,其中包含一个整数数组。您必须首先正确定义它的类:
class ResponseHolder {
private Integer[] response;
}
or
或者
class ResponseHolder {
private int[] response;
}
or
或者
class ResponseHolder {
private String[] response;
}
Then use that class while parsing your json value to a java instance:
然后在将 json 值解析为 java 实例时使用该类:
ResponseHolder responseHolder = gson.fromJson(answer, ResponseHolder.class);
回答by Asif Bhutto
BEGIN_ARRAY
but was BEGIN_OBJECT
means in the beginning it's Object not the array. If you will see in the Json, response property is the type of object and that object further contains the array. You can Parse it with different ways Using creating your own custom model class or without creating custom model class. If you don't wan't to create your Response Model class then simply parse it
BEGIN_ARRAY
但是BEGIN_OBJECT
一开始就意味着它是对象而不是数组。如果您将在 Json 中看到,响应属性是对象的类型,并且该对象进一步包含数组。您可以使用不同的方式解析它使用创建自己的自定义模型类或不创建自定义模型类。如果你不想创建你的响应模型类,那么只需解析它
final Type typeOf = new TypeToken<Map<String, List<Integer>>>() {}.getType();
final Map<String, List<Integer>> map = new Gson().fromJson(Your_JSON_String, typeOf);
// finally get list of ints form map.
final List<Integer> listOfIntegers =map.get("response");
回答by michal.luszczuk
Or use org.json included in Android:
或者使用 Android 中包含的 org.json:
JSONObject jsonData = new JSONObject(answer);
JSONArray jsonItems = jsonData.getJSONArray("response");
JSONObject jsonData = new JSONObject(answer);
JSONArray jsonItems = jsonData.getJSONArray("response");