How can I parse a JSON object from a weblink into Android and store the different values into ArrayLists?
The JSON object of users looks like the below. It comes fro
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));
You can use the native JSONObject and JSONArray present on the Android SDK here : https://developer.android.com/reference/org/json/JSONObject.html
There is a method named JSONObject(String json)
that allow you to do something like this (not tested) :
//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
}
Assuming you have a class that can store the results and appropiate constructor you can use code like below, using this json.org library for 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")));
}
}
Use GSON library to parse JSON
to java class. It is very simple to use.
Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Users.class);
Generated model example:
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;
}
You can create a Model class from your data model like:
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
}
} }
After that take a look at GSON library. Using that you can simply import the data as:
DataTemplate getTemplate(String path){
try {
return new Gson().fromJson(new InputStreamReader(dataFromURLRequest), DataTemplate.class);
} catch (Exception e) {}
After this, just directly retrieve the list from DataTemplate.