Thi*_*eka 2 java android json jsonserializer gson
我需要将JSONobj 映射到一个类及其数组ArrayList,Android并且它应该包含所有子数据.(也有嵌套的arraylists),我需要再次将更新的数据列表转换为jsonobject
我的json字符串是
{
"type": "already_planted",
"crops": [
{
"crop_id": 1,
"crop_name": "apple",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "10"
},
{
"planted_by": "A person"
}
]
},
{
"created_id": "2017-01-30",
"questions": [
{
"plants": "15"
},
{
"planted_by": "B person"
}
]
}
]
},
{
"crop_id": 2,
"crop_name": "Cashew",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "11"
},
{
"planted_by": "c person"
}
]
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
Bis*_*Abd 10
首先,您需要创建要在其中映射JSON的类.
幸运的是,有一个网站,可以为你做它在这里
其次,您可以使用谷歌Gson库轻松映射
1.添加依赖项.
dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}
Run Code Online (Sandbox Code Playgroud)
2.从您的对象到JSON.
MyData data =new MyData() ; //initialize the constructor
Gson gson = new Gson();
String Json = gson.toJson(data ); //see firstly above above
//now you have the json string do whatever.
Run Code Online (Sandbox Code Playgroud)
3.从JSON到对象.
String jsonString =doSthToGetJson(); //http request
MyData data =new MyData() ;
Gson gson = new Gson();
data= gson.fromJson(jsonString,MyData.class);
//now you have Pojo do whatever
Run Code Online (Sandbox Code Playgroud)
有关gson的更多信息,请参阅本教程.