关于使用GSON解析json对象与json数组和用gson解析json数据的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于android–使用gson解析Json返回null对象、andr
关于使用GSON解析json对象与json数组和用gson解析json数据的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于android – 使用gson解析Json返回null对象、android – 用gson解析JSON对象、Android-Gson解析JSON数据(JSON对象/JSON数组)、android-如何使用Gson解析JSON对象内的多个JSON数组?等相关知识的信息别忘了在本站进行查找喔。
本文目录一览:- 使用GSON解析json对象与json数组(用gson解析json数据)
- android – 使用gson解析Json返回null对象
- android – 用gson解析JSON对象
- Android-Gson解析JSON数据(JSON对象/JSON数组)
- android-如何使用Gson解析JSON对象内的多个JSON数组?
使用GSON解析json对象与json数组(用gson解析json数据)
我有一个JSON,它可以是单个对象或相同对象的数组。有没有一种方法可以使用Gson解析此数据,从而区分单个对象还是数组?
我目前唯一的解决方案是手动解析json并用try catch包围它。首先,我将尝试将其解析为单个对象,如果失败,它将引发异常,然后尝试将其解析为数组。
我不想手动解析它……那将使我永远。这是正在发生的事情的想法。
public class ObjectA implements Serializable{
public String variable;
public ObjectB[] objectb; //or ObjectB objectb;
public ObjectA (){}
}
这是可以是数组或单个对象的对象。
public class ObjectB implements Serializable{
public String variable1;
public String variable2;
public ObjectB (){}
}
然后在与json响应进行交互时。我在做
Gson gson = new Gson();
ObjectA[] objectList = gson.fromJson(response,ObjectA[].class);
当ObjectA的数组被序列化时,json包含ObjectB的数组或单个对象。
[
{
"variable": "blah blah","objectb": {
"variable1": "1","variable2": "2"
}
},{
"variable": "blah blah","objectb": [
{
"variable1": "1","variable2": "2"
},{
"variable1": "1","variable2": "2"
}
]
}
]
android – 使用gson解析Json返回null对象
[ { "ID": 1,"Name": "Australia","Active": true },{ "ID": 3,"Name": "Kiev",{ "ID": 4,"Name": "South Africa",{ "ID": 5,"Name": "Stockholm",{ "ID": 6,"Name": "Paris",{ "ID": 7,"Name": "Moscow",{ "ID": 8,"Name": "New York City",{ "ID": 9,"Name": "Germany",{ "ID": 10,"Name": "copenhagen",{ "ID": 11,"Name": "Amsterdam","Active": true } ]
这是将被使用的对象
public class MyBranch extends Entity { public MyBranch () { super(); } public MyBranch (int id,String name,String isActive) { super(); _ID = id; _Name = name; _Active = isActive; } @Column(name = "id",primaryKey = true) public int _ID; public String _Name; public String _Active; } Gson gson = new Gson(); Type t = new Typetoken<List<MyBranch >>() {}.getType(); List<MyBranch > list = (List<MyBranch >) gson.fromJson(json,t);
构造的列表,它有10个对象,但问题是对象的所有数据成员都是null,我不会对此有什么不妥.实体是OrmDroid的实体类.
解决方法
import com.google.gson.annotations.Serializedname; public class MyBranch extends Entity { public MyBranch () { super(); } public MyBranch (int id,String isActive) { super(); _ID = id; _Name = name; _Active = isActive; } @Column(name = "id",primaryKey = true) @Serializedname("ID") public int _ID; @Serializedname("Name") public String _Name; @Serializedname("Active") public String _Active; }
编辑:
您还可以通过简单重命名MyBranch字段来避免使用Serializedname注释:
import com.google.gson.annotations.Serializedname; public class MyBranch extends Entity { public MyBranch () { super(); } public MyBranch (int id,String isActive) { super(); ID = id; Name = name; Active = isActive; } @Column(name = "id",primaryKey = true) public int ID; public String Name; public String Active; }
android – 用gson解析JSON对象
{"response":[123123,1231231,123124,124124,111111,12314]}
有了GSON,制作
Gson gson = new GsonBuilder().create(); int[] friends = new Gson().fromJson(answer,int[].class); System.out.print(friends[0]);
但是获得错误预期BEGIN_ARRAY但在第1行第2列是BEGIN_OBJECT
如何在数组中解析这些数字?
@R_301_5609@
public class ResponseModel { private List<Integer> response = new ArrayList<Integer>(); public List<Integer> getResponse() { return response; } @Override public String toString() { return "ResponseModel [response=" + response + "]"; } }
然后你可以打电话
Gson gson = new Gson(); ResponseModel responseModel = gson.fromJson("{\"response\":[123123,12314]}",ResponseModel.class); List <Integer> responses = responseModel.getResponse(); // ... do something with the int list
Android-Gson解析JSON数据(JSON对象/JSON数组)
上一篇博客,Android-解析JSON数据(JSON对象/JSON数组),介绍了使用 org.json.JSONArray;/org.json.JSONObject; 来解析JSON数据;
Google Android 还提供来另外一种方式来解析JSON数据,那就是Gson;
Gson是非常方便的JSON解析/封装/处理等等,强大的工具类:
特点:Gson可以把JSON对象数据->转换映射为Bean对象
Gson可以把JSON数组数据->转换映射为集合
Gson可以把Bean对象->转换为JSON对象数据
Gson可以把集合->转换为JSON数组数据
...........
首先要在app/build.gradle配置文件中,导入,Gson支持包
// Gson支持包的导入
implementation ''com.google.code.gson:gson:2.6.2''
需要解析的JSON数据:
/data/data/liudeli.mynetwork01/files/pottingJSON1
{
"name":"李四",
"age":99,
"hobby":"爱好是练习截拳道"
}
/data/data/liudeli.mynetwork01/files/pottingJSONArray1
[
{
"name":"君君",
"age":89,
"sex":"男"
},
{
"name":"小君",
"age":99,
"sex":"女"
},
{
"name":"大君",
"age":88,
"sex":"男"
}
]
定义一个Bean
定义的name/age/hobby 必须要和JSON数据里面的一模一样
package liudeli.mynetwork01.entity;
/**
* 定义一个Bean
* 定义的name/age/hobby 必须要和JSON数据里面的一模一样
* {
* "name":"李四",
* "age":99,
* "hobby":"爱好是练习截拳道"
* }
*/
public class Student2 {
private String name;
private int age;
private String hobby;
public Student2(String name, int age, String hobby) {
this.name = name;
this.age = age;
this.hobby = hobby;
}
@Override
public String toString() {
return "Student{" +
"name=''" + name + ''\'''' +
", age=" + age +
", hobby=''" + hobby + ''\'''' +
''}'';
}
}
定义的name/age/sex 必须要和JSON数据里面的一模一样
package liudeli.mynetwork01.entity;
/**
* 定义一个Bean
* 定义的name/age/sex 必须要和JSON数据里面的一模一样
*
* [
* {
* "name":"君君",
* "age":89,
* "sex":"男"
* },
* {
* "name":"小君",
* "age":99,
* "sex":"女"
* },
* {
* "name":"大君",
* "age":88,
* "sex":"男"
* }
* ]
*/
public class Student {
private String name;
private int age;
private String sex;
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name=''" + name + ''\'''' +
", age=" + age +
", sex=''" + sex + ''\'''' +
''}'';
}
}
GsonAnalyzeJSONActivity.java
package liudeli.mynetwork01;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import liudeli.mynetwork01.entity.Student;
import liudeli.mynetwork01.entity.Student2;
public class GsonAnalyzeJSONActivity extends Activity {
private final String TAG = GsonAnalyzeJSONActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gson_analyze);
}
/**
* Gson解析JSON对象
* {
* "name":"李四",
* "age":99,
* "hobby":"爱好是练习截拳道"
* }
*/
public void gonsAnalyzeJSONObject(View view) {
String jsonData = readFile("pottingJSON1");
// Log.d(TAG, "jsonData:" + jsonData);
Gson gson = new Gson();
Student2 student2 = gson.fromJson(jsonData, Student2.class);
Log.d(TAG, "gonsAnalyzeJSONObject 解析后的结果:" + student2.toString());
}
/**
* Gson解析JSON数组
* [
* {
* "name":"君君",
* "age":89,
* "sex":"男"
* },
* {
* "name":"小君",
* "age":99,
* "sex":"女"
* },
* {
* "name":"大君",
* "age":88,
* "sex":"男"
* }
* ]
* @param view
*/
public void gonsAnalyzeJSONArray(View view) {
String jsonData = readFile("pottingJSONArray1");
// Log.d(TAG, "jsonData:" + jsonData);
Gson gson = new Gson();
/**
* TypeToken<List<需要映射的Bean对象>>(){}.getType()
*/
List<Student> list = gson.fromJson(jsonData, new TypeToken<List<Student>>(){}.getType()); // 参数二:需要指定类型,类型来决定解析的集合
for (Student student: list) {
Log.d(TAG, "gonsAnalyzeJSONArray 解析后的结果:" + student.toString());
}
}
/**
* 读取文件里面的字符串
* @param fileName
* @return
*/
private String readFile(String fileName) {
String result = null;
try {
InputStream inputStream = openFileInput(fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
baos.write(bytes, 0,bytes.length);
result = new String(baos.toByteArray());
baos.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
activity_gson_analyze.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gson解析JSON对象"
android:onClick="gonsAnalyzeJSONObject"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gson解析JSON数组"
android:onClick="gonsAnalyzeJSONArray"
/>
</LinearLayout>
日志的打印:
使用Gson解析,JSON对象数据:
12-23 23:00:52.108 9729-9729/liudeli.mynetwork01 D/GsonAnalyzeJSONActivity: gonsAnalyzeJSONObject 解析后的结果:Student{name=''李四'', age=99, hobby=''爱好是练习截拳道''}
使用Gson解析,JSON数组数据:
12-23 23:00:53.199 9729-9729/liudeli.mynetwork01 D/GsonAnalyzeJSONActivity: gonsAnalyzeJSONArray 解析后的结果:Student{name=''君君'', age=89, sex=''男''}
12-23 23:00:53.199 9729-9729/liudeli.mynetwork01 D/GsonAnalyzeJSONActivity: gonsAnalyzeJSONArray 解析后的结果:Student{name=''小君'', age=99, sex=''女''}
12-23 23:00:53.199 9729-9729/liudeli.mynetwork01 D/GsonAnalyzeJSONActivity: gonsAnalyzeJSONArray 解析后的结果:Student{name=''大君'', age=88, sex=''男''}
android-如何使用Gson解析JSON对象内的多个JSON数组?
这个问题已经在这里有了答案: > Parse JSON file using GSON 3个
如何使用Gson解析JSON对象内的多个JSON数组?
{
"id": 1,
"Data": {
"Details": [{
"Code": "1",
"Name": "John"
}, {
"Code": "2",
"Name": "Peter"
}],
"Other": [{
"age": "56",
"gender": "M"
}, {
"age": "66",
"gender": "M"
}]
},
"message": "SUCCESS"
}
任何帮助,将不胜感激.
解决方法:
简单!
JSONObject jsonObj = new JSONObject(yourStringHere).optJSONObject("Data");
JSONArray jsonDetail = jsonObj.optJSONArray("Details");
JSONArray jsonOther = jsonObj.optJSONArray("Other");
关于使用GSON解析json对象与json数组和用gson解析json数据的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于android – 使用gson解析Json返回null对象、android – 用gson解析JSON对象、Android-Gson解析JSON数据(JSON对象/JSON数组)、android-如何使用Gson解析JSON对象内的多个JSON数组?的相关知识,请在本站寻找。
本文标签: