如何将网络链接中的JSON对象解析为Android并将不同的值存储到ArrayLists中?
用户的JSON对象如下所示。它来自一个网站。
{"Users":[{"name":"Kane","lon":"4.371645","lat":"31.396911"},
{"name":"Sam","lon":"4.129737","lat":"31.194824"},
{"name":"Ryan","lon":"4.023134","lat":"31.298222"},
{"name":"Jerry","lon":"4.262276","lat":"31.295054"}]}
我想解析到Android并将不同的值(如name,lon和lat)存储到数组列表中。
我的最终目标是使用JSON对象在地图活动上放置标记。
答案 0 :(得分:4)
使用GSON库将JSON
解析为java类。它使用起来非常简单。
Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Users.class);
生成的模型示例:
public class Users {
@SerializedName("Users")
@Expose
public List<User> Users = new ArrayList<User>();
}
public class User {
@SerializedName("name")
@Expose
public String name;
@SerializedName("lon")
@Expose
public double lon;
@SerializedName("lat")
@Expose
public double lat;
}
答案 1 :(得分:1)
您可以从数据模型中创建一个Model类,如:
public class DataTemplate{
public final List<User> Users;
public DataTemplate(List<User> Users){
this.Users = Users;
}
public static class User{
public final String name;
public final double lon;
public final double lat;
public User(String name, double lon, double lat){
//initialize elements
}
} }
之后看一下GSON库。使用它您只需将数据导入为:
DataTemplate getTemplate(String path){
try {
return new Gson().fromJson(new InputStreamReader(dataFromURLRequest), DataTemplate.class);
} catch (Exception e) {}
在此之后,只需从DataTemplate直接检索列表即可。
答案 2 :(得分:0)
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(HttpUtil.BASIC_URL
+ HttpUtil.SUBSCRIPTION_URL);
try{
if (cookie != null) {
// httpClient.setCookieStore(LoginJsonUtil.cookie);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("uid",
uid));
nameValuePair.add(new BasicNameValuePair("subscriptionslist[pageindex]",
subscriptionslist_pageindex));
nameValuePair.add(new BasicNameValuePair("subscriptionslist[recordlimit]",
subscriptionslist_recordlimit));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
答案 3 :(得分:0)
您可以在此处使用Android SDK上的原生JSONObject和JSONArray:https://developer.android.com/reference/org/json/JSONObject.html
有一个名为JSONObject(String json)
的方法允许你做这样的事情(未经测试):
//creating your json object from your strong
JSONObject jsonObject = new JSONObject(yourString);
JSONArray users = jsonObject.getJSONArray("users");//this two lines throws a JSONException so put try{}catch{} block
for(JSON user in users)
{
JSONObject currentUser = users.get(i);
//insert yout user inside your ArrayList here
}
答案 4 :(得分:0)
假设您有一个可以存储结果的类和适当的构造函数,您可以使用以下代码,使用json.org库Java,
import org.json.*;
ArrayList<Users> users = new ArrayList<Users>();
JSONObject o = new JSONObject(jsonString);
JSONArray arr = obj.getJSONArray("Users");
for (int i = 0; i < arr.length(); i++)
{
JSONObject user = arr.getJSONObject(i);
users.add(new Users(user.getString("name"),user.getDouble("lat"),user.getDouble("lon")));
}
}