How to parse JSON Array in listview in android - android

I want to parse JSON Array and display result in listview. I have already ask in this community but didn't get helpful answer. Please give me code for this JSON.
JSON
[{
"city_id": "1",
"city_name": "Noida"
},
{
"city_id": "2",
"city_name": "Delhi"
},
{
"city_id": "3",
"city_name": "Gaziyabad"
},
{
"city_id": "4",
"city_name": "Gurgaon"
},
{
"city_id": "5",
"city_name": "Gr. Noida"
}]
URL
http://14.140.200.186/Hospital/newget_city.php
please help

As mentioned the question is too broad, just to give the approach I would take.
Build the model class in this case: City
I would advise using retrofit(http://square.github.io/retrofit/) for the network call, so build the interface
Make the network call
Add the retrieved results in a recyclerview adapter

Using Gson can do the json parsing job for you. Its easy to integrate and handy to parse json data. You simply need to create a class containing city_id and city_name.
City.java
public class City {
private String city_id;
private String city_name;
public City() {
}
public String getCityId() {
return city_id;
}
public String getCityName() {
return city_name;
}
}
Now add another class. E.g. CityList.java
import java.util.List;
public class CityList {
private List<City> cityList;
public CityList() {
}
public List<City> getCityList() {
return cityList;
}
}
Now from json string, parse the data into the CityList class.
Gson gson = new Gson();
CityList myCityList = gson.fromJson(jsonString, CityList.class);
Add the gradle dependency for Gson in build.gradle
compile 'com.google.code.gson:gson:2.3'

Related

How do I parse this Dynamo DB data into Android from an API from Amazon API Gateway?

My Code - I'm trying to return the data from JSON.
JSONObject count = new JSONObject(finalJson);
JSONArray itemsArray = count.getJSONArray("Items");
JSONObject finalObject = itemsArray.getJSONObject(0);
String record = finalObject.getString("myid");
String vocabulary = finalObject.getString("vocab");
String method = finalObject.getString("method");
return record + vocabulary + method;
JSON I'm trying to parse- Count object, Items array, etc...
{
"Count":1,
"Items":[
{
"myid":{
"S":"1"
},
"vocab":{
"S":"print a line"
},
"method":{
"S":"system.out.println"
}
}
],
"ScannedCount":1
If there is a fixed schema, you can transfer the DynamoDB JSON to JSON via a mapping template on API Gateway.
Mapping Template
#set($inputRoot = $input.path('$'))
{
"items": [
#foreach($elem in $inputRoot.Items) {
"myid": "$elem.myid.S",
"vocab": "$elem.vocab.S",
"method": "$elem.method.S"
}#if($foreach.hasNext),#end
#end
]
}
Then, you can parse the JSON String from API Gateway in your Android application into an object.
Sample parsing code
public class Items {
private List<Item> items;
//getters and setters
}
public class Item {
private String myid;
private String vocab;
private String message;
//getters and setters
}
Items items;
ObjectMapper mapper = new ObjectMapper();
jsonData = .... // from API Gateway
items = mapper.readValue(jsonData, Items.class);
Also, there is better way to get those information from API Gateway's generated android SDK. In order to do so, you need to define a Model Schema and set to the method response, then once you deploy your API change this modification, you can download an android SDK for your API.
Model Schema
{
"type": "object",
"properties": {
"items": {
"type": "array",
"item": {
"properties": {
"myid": {
"type": "string"
},
"vocab": {
"type": "string"
},
"method": {
"type": "string"
}
}
}
}
}
}
You might want to read this step by step walkthrough if you want to have more detail on how to mapping response work, and

Retrofit parse JSON dynamic keys

I'm a newbie in Retrofit. How to parse the Json below using retrofit?
{
"data": {
"Aatrox": {
"id": 266,
"title": "a Espada Darkin",
"name": "Aatrox",
"key": "Aatrox"
},
"Thresh": {
"id": 412,
"title": "o GuardiĆ£o das Correntes",
"name": "Thresh",
"key": "Thresh"
}
},
"type":"champion",
"version":"6.23.1"
}
You could make your model POJO contain a Map<String, Champion> to deserialize into, to deal with the dynamic keys.
Example:
public class ChampionData {
public Map<String, Champion> data;
public String type;
public String version;
}
public class Champion {
public int id;
public String title;
public String name;
public String key;
}
I'm not familiar with Retrofit besides that, but as someone in the comments said, the deserializing is done by Gson:
public ChampionData champions = new Gson().fromJson(json, ChampionData.class);
So to build on to the answer someone else posted, you can then do the following, assuming you've added the GsonConverterFactory:
public interface API {
#GET("path/to/endpoint")
Call<ChampionData> getChampionData();
}
Assuming Retrofit2, the first thing you need to do is call following when building your Retrofit instance.
addConverterFactory(GsonConverterFactory.create())
Then it's just a matter of writing a POJO (e.g. MyPojoClass) that maps to the json and then adding something like following to your Retrofit interface.
Call<MyPojoClass> makeRequest(<some params>);

Gson throws "BEGIN_OBJECT expected but BEGIN_ARRAY found" - how to use TypeToken

Trying out Gson for the first time instead of looping through the JSON objects for speed.
This is my input data set for parsing
{
"data": [
{
"access_token": "XXXXX",
"category": "Community",
"name": "Startup notes by Vrashabh",
"id": "XXXXX",
"perms": [
"ADMINISTER",
"EDIT_PROFILE",
"CREATE_CONTENT",
"MODERATE_CONTENT",
"CREATE_ADS",
"BASIC_ADMIN"
]
},
{
"access_token": "XXXX",
"category": "Community",
"name": "Clean Bangalore",
"id": "XXXXX",
"perms": [
"ADMINISTER",
"EDIT_PROFILE",
"CREATE_CONTENT",
"MODERATE_CONTENT",
"CREATE_ADS",
"BASIC_ADMIN"
]
},
{
"access_token": "XXXXX",
"category": "Internet/software",
"name": "Getmeetin",
"id": "XXXXX",
"perms": [
"ADMINISTER",
"EDIT_PROFILE",
"CREATE_CONTENT",
"MODERATE_CONTENT",
"CREATE_ADS",
"BASIC_ADMIN"
]
}
],
"paging": {
"cursors": {
"before": "MTU3MzE3MTA0MjkyMjY4MQ==",
"after": "MjcyMTIwMzE2Mjk3NzI5"
}
}
}
And this is my gson mapping class
public class AccountsResponse {
ArrayList<AcResponseData> data;
ArrayList<PagingData> paging;
public class AcResponseData {
public String access_token;
public String category;
public String name;
public String id;
public String[] perms;
}
public class PagingData{
public Cursors cursors;
}
public class Cursors{
public String before;
public String after;
}
}
Code for parsing the data
AccountsResponse responseAccounts = gsonResponse.fromJson(response.getRawResponse(), AccountsResponse.class);
I Know I am supposed to not expect magic in terms of data conversion, I found the other questions on SO that ask me to implement TypeToken but I couldn't get it working for this case. How do I use TypeToken to get this data into the ORM
I wouldn't mind not reading that paging data also actually, if that needs to be eliminated from the ORM
UPDATE
Changed the ORM as below but now I get
java.lang.StackOverflowError
The problem is in your AccountsResponse class. It should be an object PagingData not an ArrayList, because from the json response in your question, "paging" is a JSON object not a JSON array. So, you should declare paging as a PagingData object not as an ArrayList of PagingData objects. That should fix it.
public class AccountsResponse {
ArrayList<AcResponseData> data;
PagingData paging;
public class AcResponseData {
public String access_token;
public String category;
public String name;
public String id;
public String[] perms;
}
public class PagingData{
public Cursors cursors;
}
public class Cursors{
public String before;
public String after;
}
}
Let me know if this helps.

Gson parser class for dynamic json key value - Android

I've used gson library for parsing json response. its working well. now i got a problem .
i've got below response from webservice. the json key value is not static, it will dynamically change.
how to write a parser class to parse the below response.
Formatted JSON:
{
"meta": {
"code": 201,
"dataPropertyName": "activity",
"currentTime": "2014-02-05 06:15:04",
"listedCount": "2"
},
"activity": [
{
"comments": [
{
"raja": {
"type": "Liked",
"userPhoto": "663.png",
"userId": "74",
"userName": {
"1_0": "longjump"
},
"postOwner": "you",
"postDetails": {
"471": {
"postImage": "972.png",
"postId": "471",
"postType": "1"
}
},
"dateTime": "2014-02-05 05:24:56",
"sameOwner": "1"
}
}
]
},
{
"follow": [
{
"you": {
"type": "follow",
"followByUserName": {
"0_0": "olivepop",
"1_0": "yadidroy",
"2_0": "chitra"
},
"followUserName": "you",
"followByUserPhoto": "242.png",
"followUserPhoto": "953.png",
"dateTime": "2014-01-09 06:50:42"
}
}
]
}
],
"notifications": [
"Activities has been retrieved successfully"
]
}
Use this parser class
Meta meta = new Meta();
ArrayList<Activity> activity = new ArrayList<ActivityParser.Activity>();
ArrayList<String> notifications = new ArrayList<String>();
public class Meta
{
String code,dataPropertyName,currentTime,listedCount;
}
public class Activity
{
ArrayList<HashMap<String, CommentsItem>> comments = new ArrayList<HashMap<String,CommentsItem>>();
public class CommentsItem
{
String type,userPhoto,userId,postOwner,dateTime,sameOwner;
HashMap<String, String> userName = new HashMap<String,String>();
HashMap<String, PostDetails> postDetails = new HashMap<String,PostDetails>();
public class PostDetails
{
String postImage,postId,postType;
}
}
ArrayList<HashMap<String, FollowItem>> follow = new ArrayList<HashMap<String,FollowItem>>();
public class FollowItem
{
String type,followUserName,followByUserPhoto,followUserPhoto,dateTime;
HashMap<String, String> followByUserName = new HashMap<String,String>();
}
}
If possible get a JSON response with all possible "Key" values and then get the POJO class auto build from below link:
POJO FOR GSON
It will automatically handle all the posibilities. But make sure the RESPONCE you are providing while generating the POJO should hold all the possible combinations of your Key [changing once].
HOPE THIS HELPS!!
Depending on your specification, you can make a Default Webservice response model.java which would be something like:
String success;
#SerializedName("error_msg")
String errorMessage;
#SerializedName("error_code")
String errorCode;
JsonObject data;
where the Parent of the object with dynamic keys would be the "data".
Use Gson, map the model class:
webserviceResponse= gson.fromJson(contentResponse,WebserviceResponse.class);
if (StringUtils.isNotEmpty(webserviceResponse.getSuccess()) &&
StringUtils.equalsIgnoreCase(webserviceResponse.getSuccess(), "success")) {
//check for the dynamic key name
JsonObject job = webserviceResponse.getData();
dynamicallyDefinedKeyClass= gson.fromJson(job.get("dynamicKeyValue"), DynamicallyDefinedKeyClass.class);
}
Will edit my answer on question edit, in any way if it can help
Just a suggestion - raja, you etc. can be values for a key - name or commentsBy ? Where are you getting this response from?

Parsing complex JsonArray with GSON

Hi I already used GSON for parsing simple jsonobjects. But this time my response data is much complex. So I am struggling to parse that data.My data looks like :
[{"creator":"1", "users":[{"userName":"nilesh", "userAge":"25"},{"userName":"Me", "userAge":"25"}]},
{"creator":"2", "users":[{"userName":"nilesh", "userAge":"25"},{"userName":"Me", "userAge":"25"}]}
]
So I wrote one parsing class in following ways
public class UserData
{
#SerializedName("creator")
public String creator;
public List<Users> users;
public static class Users
{
#SerializedName("userName")
public String userName;
#SerializedName("userAge")
public String userAge;
}
}
But this is not working. Am I doing some thing wrong need some help regarding this parsing. thank you.
I tried to parse like this :
Gson gson = new Gson();
UserData users = gson.fromJson(result, UserData.class);
And it gives me error like this :
01-04 12:36:04.337: E/AndroidRuntime(15651): Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
It is because your JSON you posted is invalid.
It should be like this The posted json below is your json which is valid.
[
{
"creator": "1",
"users": [
{
"userName": "nilesh",
"userAge": "25"
},
{
"userName": "Me",
"userAge": "25"
}
]
},
{
"creator": "2",
"users": [
{
"userName": "nilesh",
"userAge": "25"
},
{
"userName": "Me",
"userAge": "25"
}
]
}
]
The json you have posted contains errors at following points
users [ should be "users" :[
userAge : should be "userAge":
This is what I was looking for
public class UserData
{
public String creator;
public List<Users> user;
public class Users
{
public String userName;
public String userAge;
}
}
and I parse in following manner
Gson gson = new Gson();
Type type = new TypeToken<List<UserData>>(){}.getType();
List<UserData > objList = gson.fromJson(result, type);

Categories

Resources