How to parse json Data Android - android

How to parse the series with same title to one array list
so i got Title name with season 1 and 2
What is the best way to do it
My Json data
{
"series":[
{
"title":"Jumping cat",
"genre":"comedy",
"year":2018,
"season":1,
"imdb":7,
"info":"comdey series",
"episodes":10,
"cover":"poster"
},
{
"title":"Jumping cat",
"genre":"comedy",
"year":2019,
"season":2,
"imdb":7,
"info":"comdey series",
"episodes":11,
"cover":"poster"
}
]
}

The following code will create a "HashMap" with String keys and ArrayList values.
The ArrayList include your model for each series:
try{
JSONObject reader = new JSONObject(str);
JSONArray array = reader.optJSONArray("series");
HashMap<String, ArrayList<YourModel>> map = new HashMap<>();
for(int i=0;i<array.length();i++){
JSONObject innerObject = array.getJSONObject(i);
if(map.get(innerObject.getString("title")) != null){ // check if the title already exists, then add it to it's list
ArrayList<YourModel> arrayList = map.get(innerObject.getString("title"));
arrayList.add(new YourModel(innerObject));
}else{ // if the title does not exist, create new ArrayList
ArrayList<YourModel> arrayList = new ArrayList<>();
arrayList.add(new YourModel(innerObject));
map.put(innerObject.getString("title"),arrayList);
}
}
}catch (JSONException e){
// Do error handling
}

If you don't want to add another 3rd party. You can do this in few lines. Yes, its manual labor, but it will save a lot of bytecode added to your APK.
public class Serie {
public String title;
public String genere;
public int year;
public int season;
public int imdb;
public String info;
public int episodes;
public String cover;
public static Serie toObject(JSONObject o) throws JSONException {
Serie s = new Serie();
s.title = o.getString("title");
s.genere = o.getString("genre");
s.year = o.getInt("year");
s.season = o.getInt("season");
s.imdb = o.getInt("imdb");
s.info = o.getString("info");
s.episodes = o.getInt("episodes");
s.cover = o.getString("cover");
return s;
}
public static List<Serie> toArray(String json) throws JSONException {
JSONObject oo = new JSONObject(json);
JSONArray a = oo.getJSONArray("series");
List<Serie> l = new ArrayList<>(a.length());
for (int i =0; i<a.length(); i++ ) {
JSONObject o = a.getJSONObject(i);
l.add(Serie.toObject(o));
}
return l;
}
}
// usage
try {
List<Serie> ll = Serie.toArray(s);
System.out.println(ll.toString());
} catch (JSONException e) {
e.printStackTrace();
}

For get the information of the Json you always will need two things
POJO's the model class ob the object you will get
Choose wich one to use or JsonParser who is native of Java or Gson who is a third party
I hope this can help you :D

Your response starts with list
#SerializedName("series")
#Expose
private List<Series> series = null;
List model class
#SerializedName("title")
#Expose
private String title;
#SerializedName("genre")
#Expose
private String genre;
#SerializedName("year")
#Expose
private Integer year;
#SerializedName("season")
#Expose
private Integer season;
#SerializedName("imdb")
#Expose
private Integer imdb;
#SerializedName("info")
#Expose
private String info;
#SerializedName("episodes")
#Expose
private Integer episodes;
#SerializedName("cover")
#Expose
private String cover;
And create getter setter method

You can use Google's gson library for simply parse json into java classe and vice versa. An example for how to use gson found here

Related

How to get data from nested JSON objects using Gson

I would like get countynames from the API and it returns nested objects;
"countries": {
"1": {
"name": "Cyprus",
"nameTurkish": "KKTC",
"nameNative": "Kıbrıs"
},
"2": {
"name": "Turkey",
"nameTurkish": "Türkiye",
"nameNative": "Türkiye"
},
"3": {
"name": "Monaco",
"nameTurkish": "Monako",
"nameNative": "Monaco"
},
and so on there are more than 200 countries and every county has its own "NUMBER_ID". In the end I want to list all "name" information. I think I should use JsonDeserializer but unfortunately I couldn't.
The entire JSON response can be read as a JSONObject that has multiple elements in it that you can iterate through and get different data.
String jsonResponse = ""; // Put the entire JSON response as a String
JSONObject root = new JSONObject(jsonResponse);
JSONArray rootArray = root.getJSONArray("countries"); // root element of the json respons
for (int i = 0; i < rootArray.length(); i++) {
JSONObject number = rootArray.getJSONObject(i);
String country = number.getString("name"); // Get country name
// Here you can add `country` into a List
}
UPDATE:
but there is no array in my JSON file, all of them are objects, every
country is in an object and every object has its own SerializedName
You can read it into JSONOjbect, and instead of using a JSONArray, you can iterate over the length of the JSONObject as below.
try {
JSONObject root = new JSONObject(jsonResponse);
JSONObject countries = root.getJSONObject("countries");
for (int i = 1; i <= countries.length(); i++) {
JSONObject number = countries.getJSONObject(String.valueOf(i));
String country = number.getString("name"); // Get country name
// Here you can add the `country` into a List
}
} catch (JSONException e) {
e.printStackTrace();
}
try using TypeToken.
Gson gson = new Gson();
List<Country> list = gson.fromJson(gson.toJson(what_you_get_data), new TypeToken<ArrayList<Country>>(){}.getType()); //Country is VO class what you make.
Here, you can see that your data looks like HashMap, so I just tried in that way and your data parsed successfully without a glitch:
Create Pojo's:
public class Countries {
private HashMap<String, Country> countries;
public HashMap<String, Country> getCountries() { return countries; }
public void setCountries(HashMap<String, Country> countries) { this.countries = countries; }
}
public class Country {
private String name;
private String nameTurkish;
private String nameNative;
public String getName() { return name; }
public void setName(String name) { this.name = name;}
public String getNameTurkish() { return nameTurkish; }
public void setNameTurkish(String nameTurkish) { this.nameTurkish = nameTurkish; }
public String getNameNative() { return nameNative; }
public void setNameNative(String nameNative) { this.nameNative = nameNative; }
}
Create a Gson Object and parse it:
Gson gson = new Gson();
// Countries Object
Type testC = new TypeToken<Countries>(){}.getType();
Countries ob = gson.fromJson(test, testC);
String newData = gson.toJson(ob.getCountries());
System.out.println("New Data: "+newData);
// All country in HashMap
Type country = new TypeToken<HashMap<String, Country>>(){}.getType();
HashMap<String, Country> countryHashMap = gson.fromJson(newData, country);
// Print All HashMap Country
for (Map.Entry<String, Country> set : countryHashMap.entrySet()) {
System.out.println("==> "+set.getKey() + " = " + set.getValue());
}
Output:
I/System.out: ==> 1 = Country{name='Cyprus', nameTurkish='KKTC', nameNative='Kıbrıs'}
I/System.out: ==> 2 = Country{name='Turkey', nameTurkish='Türkiye', nameNative='Türkiye'}
I/System.out: ==> 3 = Country{name='Monaco', nameTurkish='Monako', nameNative='Monaco'}

how to get json values in an array

I am completely don't know Json. Now i am working in Android project. I know how to use Array. I have Json file inside of my Asset folder in my Android Project.
and i have to fetch only standard value from json data and store it in an empty array. my json data is,
[
{
"name":"aaa",
"surname":"bbb",
"age":"18",
"div":"A",
"standard":"7"
},
{
"name":"ccc",
"surname":"ddd",
"age":"17",
"div":"B",
"standard":"7"
},
{
"name":"eee",
"surname":"fff",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"ggg",
"surname":"hhh",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"sss",
"surname":"ddd",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"www",
"surname":"ggg",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"ggg",
"surname":"ccc",
"age":"18",
"div":"B",
"standard":"6"
}
]
i am not able to get the way through which i can do this. because i have to check each standard in json data and add it to the array created for storing standard valuee so that i can compare that standard values with each satndard values if its already present in array the it can check the next index in josn data and accordingly unique values can get stored on may array.
i dont know to achieve this as i am new to android as well as for json.
Use gson for easy parsing of json
TypeToken> token = new TypeToken>() {};
List animals = gson.fromJson(data, token.getType());
you can use http://www.jsonschema2pojo.org/ to create user class
public class User {
#SerializedName("name")
#Expose
private String name;
#SerializedName("surname")
#Expose
private String surname;
#SerializedName("age")
#Expose
private String age;
#SerializedName("div")
#Expose
private String div;
#SerializedName("standard")
#Expose
private String standard;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getDiv() {
return div;
}
public void setDiv(String div) {
this.div = div;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
}
You can do this way:
//Global Declared
ArrayList<String> allStanderds = new ArrayList<>();
allStanderds.clear();
try{
JSONArray araay = new JSONArray(Your_Json_Array_String);
for (int i = 0; i <array.length() ; i++) {
JSONObject jsonObject = new array.getJSONObject(i);
String standard = jsonObject.getString("standard");
if(!allStanderds.contains(standard)){
allStanderds.add(standard);
}
}
}catch (Exception e) {
e.printStackTrace();
}
// use allStanderds ArrayList for SetAdapter for Spinner.
Happy Coding > :)
Use GSON for parsing JSON array.GSON will provide very helpful API
See my previously asked question on SO related to JSON parsing. You will get rough idea
How to parse nested array through GSON
installl GsonFormat plugin in android studio
use your json string to generate an user entity(example:UserEntity.class)
now,you can use UserEntity user=new Gson().fromJson(yourString,UserEntity.class);
now,your json string is storaged in Object user now;
Please try to use this one
try{
String assestValue = getStringFromAssets();
JSONArray arr = new JSONArray(assestValue);
int count = arr.length();
for (int i=0; i < count; i++){
JSONObject obj = arr.getJSONObject(i);
String name = obj.getString("name");
String surname = obj.getString("surname");
String age = obj.getString("age");
String div = obj.getString("div");
String standard = obj.getString("standard");
}
}catch (JSONException e){
e.printStackTrace();
}
public String getStringFromAssets(){
String str = "";
try {
StringBuilder buf = new StringBuilder();
InputStream json = getAssets().open("contents.json");//put your json name
BufferedReader in =
new BufferedReader(new InputStreamReader(json, "UTF-8"));
while ((str = in.readLine()) != null) {
buf.append(str);
}
in.close();
return str;
}catch (Exception e){
e.printStackTrace();
}
return str;
}
Enjoy programming :)

facing some difficulty in json parsing

My json response is below
{
"groups":[
{
"storeId":"440f0991-9ac5-41b9-9e84-d3b2a2d27c13",
"name":"oty",
"description":"ga",
"image":null,
"bookCount":2,
"members":[
{
"bookId":"9b765d0f-3d6f-4fc1-a4a7-af807c39a004",
"bookName":"Anantha"
},
{
"bookId":"f8616ab1-eeb3-403b-8182-b42e39f4b948",
"bookName":"lok"
}
]
}
]
}
My code for parsing json
JSONObject jsonObject = new JSONObject(message);
JSONArray jsonArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < jsonArray.length(); i++) {
String storeid = jsonArray.getJSONObject(i).getString("storeId");
String name = jsonArray.getJSONObject(i).getString("name");
String description =jsonArray.getJSONObject(i).getString("description");
String bookCount = jsonArray.getJSONObject(i).getString("bookCount");
JSONArray memberJsonArray = jsonArray.getJSONObject(i).getJSONArray("members");
for (int j = 0; j < memberJsonArray.length(); j++) {
String bookId = memberJsonArray.getJSONObject(j).getString("bookId");
String bookName = memberJsonArray.getJSONObject(j).getString("bookName")
GroupsDto groupDtoData = new GroupsDto();
groupDtoData.setGroupName(name);
groupDtoData.setGroupServerId(storeId);
groupDtoData.setbookname(bookName);
groupDtoData.setbookid(bookId);
groupDto.add(groupDtoData);
db.addGroups(groupDtoData);
}
}
but I got result as if book name is twice then the storeId is also twice.simillarly increse in no of book name,store id also increse.so it reflect on the list view having duplicate store name.
I/System.out: storeId 440f0991-9ac5-41b9-9e84-d3b2a2d27c13
I/System.out: bookName Ananta
I/System.out: storeId groupid440f0991-9ac5-41b9-9e84-d3b2a2d27c13
I/System.out: bookname Lok
But i want with one storeId there are two book name but store id also getting twice
please give some idea how to parse this type of json.I have facing this problem for json parsing But i want with one storeId there are two book name but store id also getting twice
Serialize and De-serialize using Gson.
1. Create a model Class, for your case would look like below.
public class MyResponse {
#SerializedName("groups")
private List<Groups> groupsList;
public List<Groups> getGroupsList() {
return groupsList;
}
public class Groups {
#SerializedName("storeId")
private String storeId;
#SerializedName("name")
private String name;
#SerializedName("description")
private String description;
#SerializedName("bookCount")
private String bookCount;
#SerializedName("members")
private List<Members> members;
public String getStoreId() {
return storeId;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getBookCount() {
return bookCount;
}
public List<Members> getMembers() {
return members;
}
public class Members {
#SerializedName("bookId")
private String bookId;
#SerializedName("bookName")
private String bookName;
public String getBookName() {
return bookName;
}
public String getBookId() {
return bookId;
}
}
}
}
Make sure you add Gson Lib on your gradle file if using android studio
dependencies {
compile 'com.google.code.gson:gson:2.6.2'
}
Use the response String, for your case is the message object and convert it to a response object like below.
Gson gson = new GsonBuilder().create();
MyResponse myResponse = gson.fromJson(message, MyResponse.class);

Get Specific JSON Object based on TextView

I am a newbie in android developers and
I need help to get a specific object based on a text on TextView and show it on another TextView.
Here is my JSON data:
{
"card_data": [{
"card_id": "123456",
"balance": "100000"
}, {
"card_id": "654321",
"balance": "50000"
}]
}
For example on my TextView1 I have "123456".
How can I display "100000" on TextView2?
First create setter and getter for your json. See below code.
private class CardInfo
{
private String cardId;
private String balance;
public CardInfo(String cardId, String balance) {
this.cardId = cardId;
this.balance = balance;
}
public String getCardId() {
return cardId;
}
public String getBalance() {
return balance;
}
}
Then create JsonParser for your Json Object and add json obj as a CardInfoObj in ArrayList.
private ArrayList<CardInfo> mList = new ArrayList<>();
private void jsonParser()
{
try {
JSONObject jsonObject = new JSONObject("{\n" +
"\t\"card_data\": [{\n" +
"\t\t\"card_id\": \"123456\",\n" +
"\t\t\"balance\": \"100000\"\n" +
"\t}, {\n" +
"\t\t\"card_id\": \"654321\",\n" +
"\t\t\"balance\": \"50000\"\n" +
"\t}]\n" +
"}");
JSONArray jsonArray = jsonObject.getJSONArray("card_data");
for(int i=0;i<jsonArray.length(); i++)
{
JSONObject user = jsonArray.getJSONObject(i);
mList.add(new CardInfo(user.get("card_id").toString(), user.get("balance").toString()));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Now In mList having cardId and balance for each json obj. now get cardinfo obj from mList.
private void setText()
{
CardInfo cardInfo = mList.get(0);// get specfice obj based on your requirement.
mTvCard.setText(cardInfo.getCardId());
mTvBalance.setText(cardInfo.getBalance());
}
You need to know the data type of json field. If balance is Integer type then extract integer from json and convert it to string type using String.valueOf("100000"). Now you can set the value on textfield.

gson to POJO object, not working properly

I am developing an Android application and I access a RESTfull web service that returns a JSON. This JSON I want to put it in POJOs but I think I am missing something as it doesn't work.
The JSON retuned is as follow:
[{"CategoryName":"Food","Id":1},{"CategoryName":"Car","Id":2},{"CategoryName":"House","Id":3},{"CategoryName":"Work","Id":4}]
this is returned in response variable
String response = client.getResponse();
And now I try the following:
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
JSONObject j;
MainCategories cats = null;
try
{
j = new JSONObject(response);
cats = gson.fromJson(j.toString(), MainCategories.class);
}
catch(Exception e)
{
e.printStackTrace();
}
The error I get is:
09-02 07:06:47.009:
WARN/System.err(568):
org.json.JSONException: Value
[{"Id":1,"CategoryName":"Food"},{"Id":2,"CategoryName":"Car"},{"Id":3,"CategoryName":"House"},{"Id":4,"CategoryName":"Work"}]
of type org.json.JSONArray cannot be
converted to JSONObject
09-02 07:06:47.029:
WARN/System.err(568): at
org.json.JSON.typeMismatch(JSON.java:107)
Here are the POJO objects
MainCategories.java
public class MainCategories {
private List<CategoryInfo> category;
public List<CategoryInfo> getCategory() {
if (category == null) {
category = new ArrayList<CategoryInfo>();
}
return this.category;
}
}
CategoryInfo.java
public class CategoryInfo {
public String categoryName;
public Integer id;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String value) {
this.categoryName = ((String) value);
}
public Integer getId() {
return id;
}
public void setId(Integer value) {
this.id = value;
}
}
To access the web service I use the class from: http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
Please help me as I am stuck for 2 days now and can't figure out how to continue. I found some subjects here but still didn't found a way around. Thank you very much.
Top level entity in your JSON string is JSONArray not JSONObject, while you're trying to parse it as object. Create an array from the string and use that.
JSONArray array = new JSONArray(response);

Categories

Resources