Get Specific JSON Object based on TextView - android

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.

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 parse json Data 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

How do I modify my function to retrieve json objects to a nested json?

Here's the json I currently use in my code :
{"forceDeviceLockout":0,"canStartValue":true,"destructOnRead":[30,60,300]}
I use the following function to get the json values:
private Object getValueForField(Field field) {
if (runtimeConfiguration.has(field.fieldName) && field.updateFromServer) {
try {
Object value = runtimeConfiguration.get(field.fieldName);
if (value instanceof JSONArray) {
JSONArray values = (JSONArray) value;
if (values.get(0) instanceof Number) {
long[] retVals = new long[values.length()];
for (int i = 0; i < values.length(); i++) {
retVals[i] = ((Number) values.get(i)).longValue();
}
return retVals;
}
} else if (value instanceof Number) {
return ((Number) value).longValue();
} else {
return value;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return field.defaultValue;
}
Now, I have a new nested json as follows:
{"forceDeviceLockout":0,"canStartValue":true,"destructOnRead":[30,60,300],"NEWVALUE":{"canStartNewValue1":true,"canStartroupValue":true}
In the new json I am adding the nested json object : NEWVALUE which has 2 objects within itself.
I am a little weak at json so unsure how to go about modifying my code to retrieve the above individual values. Any ideas?
I don't know why are you making it so complicated! but see this code I wrote for you. it might give you an idea:
public void printFieldsValues(Object object){
try{
Field[] fields = object.getClass().getFields();
JSONObject jsonObject = new JSONObject();
for(Field field : fields){
jsonObject.put(field.getName(), field.get(object));
}
JSONObject newValue = new JSONObject("{\"canStartNewValue1\":true,"
+ "\"canStartroupValue\":true}");
jsonObject.put("NEWVALUE", newValue);
printJson(jsonObject);
}catch(Exception e){
e.printStackTrace();
}
}
public void printJson(JSONObject jsonObject) throws JSONException{
Iterator<String> keys = jsonObject.keys();
String key;
while(keys.hasNext()){
key = keys.next();
try{
printJson(new JSONObject(jsonObject.getString(key)));
}catch(Exception e){
Log.d("TAG", "key = " + key);
Log.d("TAG", "value = " + jsonObject.get(key).toString());
}
}
}
and in your main Object you can call it like this:
printFieldsValues(this);
If those json keys are predefined we can access them like this
public class SampleModel {
public int forceDeviceLockout;
public boolean canStartValue;
public int[] destructOnRead;
public NestedModel NEWVALUE;
}
public class NestedModel {
public boolean canStartNewValue1;
public boolean canStartroupValue;
}
Gson gson = new Gson();
SampleModel sampleModel = gson.fromJson("{\"forceDeviceLockout\":0,\"canStartValue\":true,\"destructOnRead\":[30,60,300],\"NEWVALUE\":{\"canStartNewValue1\":true,\"canStartroupValue\":true}}",SampleModel.class);
Log.d("canStartNewValue : " ,sampleModel.canStartNewValue)
Log.d("canStartNewValue1 : " , sampleModel.NEWVALUE.canStartNewValue1);
Note : Need to add dependency compile 'com.google.code.gson:gson:2.8.2'
If you just want to modify your current code to parse the json received you could just add
if(value instance of JSONObject){
JSONObject jsonObject = (JSONObject) value;
return jsonObject;
}

How to read this json in android? I am confused with jsonobject and json string

I am confused as to what a JSON Object is and what a JSON String is. Which part is a JSON Object, and which is a JSON String?
JSON example 1:
{
"abc":"v1",
"def":"v2"
}
JSON example 2:
{
"res":"false",
"error":{
"code":101
}
}
Given by your first example:
try {
JSONObject obj = new JSONObject(json);
String abc = obj.get("abc");
String def = obj.get("def");
} catch (Throwable t) {
// Log something maybe?
}
Simply create a JSONObject with that string in the constructor.
JSONObject obj = new JSONObject(your_string_goes_here);
Your JSON string is the entire visual representation that you see (encoded as a string):
{
"abc":"v1",
"def":"v2"
}
You can tell where a specific JSON Object starts and ends within your string, by looking for that opening brace { and the closing brace '}'.
In your examples, this is a JSON Object:
{
"abc":"v1",
"def":"v2"
}
So is this:
{
"res":"false",
"error": {
"code":101
}
}
And this:
{
"code":101
}
Use GSON for parsing & below are the model classes for json1 & json2
public class Json1 {
/**
* abc : v1
* def : v2
*/
private String abc;
private String def;
public String getAbc() {
return abc;
}
public void setAbc(String abc) {
this.abc = abc;
}
public String getDef() {
return def;
}
public void setDef(String def) {
this.def = def;
}
}
Json2
public class Json2 {
/**
* res : false
* error : {"code":101}
*/
private String res;
/**
* code : 101
*/
private ErrorBean error;
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public ErrorBean getError() {
return error;
}
public void setError(ErrorBean error) {
this.error = error;
}
public static class ErrorBean {
private int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
}
I have used GsonFormatter plugin for creating model classes, Use Gson, It is super easy and you dont need to parse anything
JSON comprises JSONObject & JSONArray.
Json-1 is JSONObject while JSON -2 is also JSONObject which contains another JSONObject with a key "error".JSON String is the string representation of JSONObject which you can get by JSONObject jsonObject = new JSONObject(); String jsonString = jsonObject.toString();
Data is represented in name/value pairs.
"abc":"v1"
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma).
{
"abc":"v1",
"def":"v2"
}
Code Example:
JSONObject obj = new JSONObject(jsonStr);
String abc = obj.get("abc");
Square brackets hold arrays and values are separated by ,(comma).
{
"books": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt",
},
{
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy",
}
]
}
Code Example:
JSONArray arrBooks = new JSONArray("books");
for (int i = 0; i<=arrBooks.length(); i++){
JSONObject objBook = arrBooks.getJSONObject(i);
String id = c.getString("id");
}

Android json processing

I'm reading json and it works fine.
But it's failed to add resulting String into the ArrayList.
Any ideas why ?
Here is the code.
StuffPics class (updated):
public class StuffPics {
private String imageUrl;
public StuffPics() {
}
public String getImageUrl() {
return imageUrl;
}
public String setImageUrl(String imageUrl) {
return this.imageUrl;
}
#Override
public String toString() {
return "StuffPics = " + this.imageUrl;
}
}
Activity (updated):
private ArrayList<StuffPics> mylist;
...
protected void onPostExecute(String result) {
try{
String url="http://www.test.com";
JSONArray jsonarray = new JSONArray(result);
int lengthJsonArr = jsonarray.length();
for (int i = 0; i < lengthJsonArr; i++)
{
//build url
JSONObject jsonChildNode = jsonarray.getJSONObject(i);
String autcElement = jsonChildNode.optString("picUrl").toString();
String img= url + autcElement;
System.out.println("imageUrl"+img);
//create object and add it to the list
StuffPics pic = new StuffPics();
pic.getImageUrl();
System.out.print("PIC"+pic);
mylist.add(pic);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
So, the first System.out shows strings, as they should be. Means json was read the right way.
But the second System.out shows nothing. Means I can't add strings into StuffPics pic. As the result ArrayList mylist is empty as well.
What am I doing wrong ?
Well pic is a custom object StuffPics .
You will need to override toString() in order to see something
for example:
#Override
public String toString() {
return "StuffPics = " + this.imageUrl;
}
also make sure mylist is initialized and you can adjust your code like this:
try{
String url="http://www.test.com";
JSONArray jsonarray = new JSONArray(result);
int lengthJsonArr = jsonarray.length();
for (int i = 0; i < lengthJsonArr; i++)
{
//build url
JSONObject jsonChildNode = jsonarray.getJSONObject(i);
String autcElement = jsonChildNode.optString("picUrl").toString();
String img= url + autcElement;
System.out.println("imageUrl"+img);
//create object and add it to the list
StuffPics pic = new StuffPics();
pic.setImageUrl(img);
System.out.print("PIC"+pic.toString());
mylist.add(pic);
}
}
catch (Exception e) {
e.printStackTrace();
}
You can use Gson
to view your custom objects.son is a Java library that can be used to convert Java Objects into their JSON representation.
simply convert your object to a json using:
String json = new Gson().Json(pic);
and print it using logs.
Replace this line:
System.out.print("PIC"+pic);
with that:
System.out.print("PIC"+pic.getImageUrl());
Your list is not empty, you are only not able to see the URL you added.

Categories

Resources