JSON Parsing for Android - android

Let us suppose that we have the following JSON format which is a bit complicated.
items: [
{
kind: "customsearch#result",
title: "Flower - Wikipedia, the free encyclopedia",
htmlTitle: "<b>Flower</b> - Wikipedia, the free encyclopedia",
link:
"http://upload.wikimedia.org/wikipedia/commons/a/a5/Flower_poster_2.jpg",
displayLink: "en.wikipedia.org",
snippet: "Flower - Wikipedia, the free",
htmlSnippet: "<b>Flower</b> - Wikipedia, the free",
mime: "image/jpeg",
image: {
contextLink: "http://en.wikipedia.org/wiki/Flower",
height: 5932,
width: 4462,
byteSize: 4487679,
thumbnailLink: "https://encrypted-tbn3.gstatic.com/images?
q=tbn:ANd9GcQdv1k3rb2HdBbQy9rEt_LX-PNnOd9uZ-O0PExeAJQfgoPxUna6pzS6ivfU",
thumbnailHeight: 150,
thumbnailWidth: 113
}
}
]
I also have the following simple class.
public class WebImage {
private String mUrl;
private String mThumbnailUrl;
public WebImage(String url, String thumbnailUrl) {
mUrl = url;
mThumbnailUrl = thumbnailUrl;
}
public String getUrl() {
return mUrl;
}
public String getThumbnailUrl() {
return mThumbnailUrl;
}
#Override
public String toString() {
return mUrl + " | " + mThumbnailUrl;
}
}
I am interested in the "items" JSON array. Every item in the array contains an image "link" and an "image" JSON object with the "thumbnailLink".
private static List<WebImage> parseJsonResponse(String jsonResponse) throws
JSONException {
List<WebImage> webImages = new ArrayList<WebImage>();
// TODO: perform the parsing.
return webImages;
}
How should I read the objects? I am a bit confused with that one.
Thank you,
Theo.

items is JSONArray of JSONObject and every JSONObject contain image JSONObject. Get both link and thumbnailLink as:
JSONArray array =new JSONArray(jsonResponse);
List<WebImage> webImages = new ArrayList<WebImage>();
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// get link from object
String strLink= object.optString("link");
// get image JSONObject
JSONObject objectInner = object.getJSONObject("image");
// get thumbnailLink from objectInner
String strthumbnailLink= object.optString("thumbnailLink");
WebImage objWebImage=new WebImage(strLink,strthumbnailLink);
// add objWebImage to ArrayList
webImages.add(objWebImage);
}

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 obtain and convert custom json data as strings in android

I've googled around and found many tutorials(duplicates) and tips about json for android, but I find it difficult to perceive. I find it hard to get the score and the names as strings from the following json that I've retrieved from my database. I tried to get the result object first and get the names and scores but not certain how I can get manage to get it from [{},{}].
Are there some easy examples or tips? It sounds silly, but I need your help. I would like to hear from you!
{
"result": [
{
"id": "3",
"name": "Bobby",
"score": "44"
},
{
"id": "2",
"name": "Mike",
"score": "10"
}
]
}
Let,
String s = "{"result": [{"id": "3","name": "Bobby","score": "44"},{"id": "2","name": "Mike","score": "10"}]}";
JSONObject jsonObject = new JSONObject(s);
JSONArray result= jsonObject .getJSONArray("result");
for(int i = 0; i < result.length(); i++) {
JSONObject json = result.getJSONObject(i);
String name = json.getString("name");
String score = json.getString("score");
}
it's so simply
Just do like this
first make a model for according to your need like id, name and score
then use this
JSONObject jObj = new JSONObject(response.toString());
JSONArray results = jObj.getJSONArray("result");
now the values are in array use that array to show values
In json {} means object and [] means array.
First you should create a Json object from your string. Then get result as an array. In result you have tow objects that you can get them with their index.
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result= jsonObject .getJSONArray("result");
// Now we can iterate through the array
for(int i = 0; i < result.length(); i++) {
JSONObject item = (JSONObject) result.get(i);
String name = item.getString("name");
String score = item.getString("score");
}
Use GSON to deserialize from JSON to a Plain Old Java Object (POJO).
Include GSON library in your Android project:compile 'com.google.code.gson:gson:2.8.0'
Create your JAVA POJO model:
public class MyClass {
#SerializedName("result")
private List mResult;
public List<Result> getResults() {
return mResult;
}
private static class Result {
#SerializedName("id")
private String mId;
#SerializedName("name")
private String mName;
#SerializedName("score")
private String mScore;
public String getId() {
return mId;
}
public String getName() {
return mName;
}
public String getScore() {
return mScore;
}
}
}
Deserialize your JSON to your POJO object:
Gson gson = new Gson();
gson.fromJson(you_json_string, MyClass.class);
Once you have your deserialized object you just need to call your getters:
getResults().get(0).getScore()

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.

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