How to get the particular data object from the JSON data from the given JSON data:
{
"customer":{
"id":1117198024800,
"email":"abc#gmail.com",
"accepts_marketing":false
}
}
I need to parse ID from the above data, Can anyone help me please. Thanks in advance!!!
If you will use it as string:
JSONObject reader = new JSONObject(data);
JSONObject customer = reader.getJSONObject("customer");
String id = (String) customer.getString("id");
Use this
JSONObject responceObj = new JSONObject(data);
JSONObject customer= response.getJSONObject("customer");
String id= customer.getString("id");
String email= customer.getString("email");
String accepts_marketing= customer.getString("accepts_marketing");
add to app/build.gradle:
dependencies {
...
implementation "com.google.code.gson:gson:2.8.1"
}
In code:
String string = "{
\"customer\":{
\"id\":1117198024800,
\"email\":\"abc#gmail.com\",
\"accepts_marketing\":false
}
}";
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<HashMap<String,Customer>>() {}.getType();
HashMap<String, Customer> hashMap = new Gson().fromJson(string, type).
Customer customer = hashMap.get("customer");
Customer.java class:
public class Customer{
Long id;
String email;
Boolean acceptsMarketing;
}
Related
I have a JSON Object I want to parse at this URL https://api.adviceslip.com/advice with this content:
{"slip": { "id": 137, "advice": "You're not that important; it's what you do that counts."}}
I have written this code in Android Studio but it does not seem to work.
String jsonString = handler.httpServiceCall(url);
if (jsonString != null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject slip = jsonObject.getJSONObject("slip");
String id = slip.getString("id");
Log.d("slip id:", id);
String advice = slip.getString("advice");
Log.d("slip adv:", advice);
HashMap<String, String> map = new HashMap<>();
map.put("id", id);
map.put("advice", advice);
adviceSlip.setText(map.get("advice"));
}
Any help would be appreciated :)
One problem is that you are trying to get a String on an Int object, and perhaps this is one of your errors, please change your
splip.getString("id");
by
slip.getInt("id);
Another one is that you are creating a HashMap<String,String> but the id you getting from the json is an Int and perhaps you should change it to use HashMap<Int,String>
You can get the value from the jsonobject and simple set that value on the textview.
String jsonString = handler.httpServiceCall(url);
if (jsonString != null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject slip = jsonObject.getJSONObject("slip");
String id = slip.getString("id");
Log.d("slip id:", id);
String advice = slip.getString("advice");
adviceSlip.setText(advice);
}
I have a nested JSON array from which I need to retrieve values of all Usernames nested within Friends.
{
"Friends": [
{"Username": "abc"},
{"Username": "xyz"}
]
}
After I get all the usernames, I want to store it in a List that I will use with an adapter and ListView.
FriendList.java:
public class FriendList
{
#SerializedName("Username")
private String username;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}
This is the code that I have written so far:
if (httpResult != null && !httpResult.isEmpty()) //POST API CALL
{
Type listType = new TypeToken<List<FriendList>>() {}.getType();
List<FriendList> friendList = new Gson().fromJson(httpResult, listType);
FLCustomAdapter adapter = new FLCustomAdapter(getActivity(), friendList);
mainFriendsListView.setAdapter(adapter);
}
However, an error occurs: Failed to deserialize Json object.
Please suggest, what additions/changes should be made to it, so that I can retrieve nested JSON values into a list?
First of all, You have to understand the strucure of this Json.
You can see, it contains
1 . A json object
2 . This json object contains a json array which can include several different json objects or json arrays.
In this case, it contains json objects.
Parsing:
Get the Json Object first
try{
JSONObject jsonObject=new JSONObject(jsonResponse);
if(jsonObject!=null){
//get the json array
JSONArray jsonArray=jsonObject.getJSONArray("Friends");
if(jsonArray!=null){
ArrayList<FriendList> friendList=new ArrayList<FriendList>();
//iterate your json array
for(int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
FriendList friend=new FriendList();
friend.setUserName(object.getString(Username));
friendList.add(friend);
}
}
}
}
catch(JSONException ex){
ex.printStackTrace();
}
hope, it will help you.
Solution with GSON.
You need to two class to parse this.
FriendList and UsernameDao.
public class UsernameDao {
#SerializedName("Username")
private String username;
//get set methods
}
Simple Json Parsing would be like this
JSONObject params=new JSONObject(httpResult);
JSONObject params1=params.getJsonObject("Friends");
JsonArray array=params1.getJsonArray();
for(int i=0;i<array.length();i++)
{
String userName=array.getJsonObject(i).getString("UserName");
// Do whatever you want to do with username
}
Following code works good without any use of GSON , Please try .
String jsonString = "Your Json Data";
JSONObject jsonRootObject = new JSONObject(jsonString );
JSONArray friendsArray = jsonRootObject .getJSONArray("Friends");
ArrayList<FriendList > friendsList = new ArrayList<FriendList >();
for(int friendsLen = 0 ;friendsLen < friendsArray .length() ; friendsLen ++){
FriendList userNameObj = new UserName();
JSONObject jsonObj = jsonRootObject.getJSONObject(friendsLen ) ;
String Username = jsonObj.getString("Username");
userNameObj .setUserName(Username );
friendsList .add(userNameObj );
}
Now friendsList the list which you want .
List<FriendList> friendList = new Gson().fromJson(httpResult, listType);
This cannot work because it expects your whole JSON document to be just an array of FriendList element (by the way, why "FriendList"?): [{"Username": "abc"},{"Username": "xyz"}] -- this is what can be parsed by your approach.
The easiest solution to fix this (apart from harder to implement but more efficient streamed reading in order to peel of possible unnecessary properties) is just creating a correct mapping:
final class Wrapper {
#SerializedName("Friends")
final List<Friend> friends = null;
}
final class Friend {
#SerializedName("Username")
final String username = null;
}
Now deserialization is trivial and you don't have to define a type token because Gson has enough information for the type from the Wrapper.friends field:
final Wrapper wrapper = gson.fromJson(response, Wrapper.class);
for ( final Friend friend : wrapper.friends ) {
System.out.println(friend.username);
}
Output:
abc
xyz
Change List<FriendList> friendList = new Gson().fromJson(httpResult, listType);
to
FriendList friends = new Gson().fromJson(httpResult, listType);
List<Friend> friends = friends.list;
Updated FriendList.java as mentioned below
FriendList.java
public class FriendList
{
#SerializedName("Friends")
public List<Friend> list;
}
Friend.java
public class Friend
{
#SerializedName("Username")
private String username;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}
How to parse below Json Response with google Gson.?
{
"rootobject":[
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
},
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
},
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
},
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
}
]
}
I'd create objects to "wrap" the response, such as:
public class Response {
#SerializedName("root_object")
private List<YourObject> rootObject;
//getter and setter
}
public class YourObject {
#SerializedName("id")
private String id;
#SerializedName("name")
private String name;
#SerializedName("subtitle")
private String subtitle;
//... other fields
//getters and setters
}
Note: use #SerializedName annotation to follow naming conventions in your Java attribute while matching the names in the JSON data.
Then you just parse the JSON with your Reponse object, like this:
String jsonString = "your json data...";
Gson gson = new Gson();
Response response = gson.fromJson(jsonString, Response.class);
Now you can access all the data in your Response object using getters and setters.
Note: your Response object may be used to parse different JSON responses. For example you could have JSON response that don't contain the id or the subtitle fields, but your Reponseobject will parse the response as well, and just put a null in this fields. This way you can use only one Responseclass to parse all the possible responses...
EDIT: I didn't realise the Android tag, I use this approach in a usual Java program, I'm not sure whether it's valid for Android...
You can try this hope this will work
// Getting Array
JSONArray contacts = json.getJSONArray("rootobject");
SampleClass[] sample=new SampleClass[contacts.length]();
// looping through All
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
sample[i].id = c.getString("id");
sample[i].name = c.getString("name");
sample[i].email = c.getString("subtitle");
sample[i].address = c.getString("key1");
sample[i].gender = c.getString("key12");
sample[i].gender = c.getString("location");
sample[i].gender = c.getString("key13");
sample[i].gender = c.getString("key14");
sample[i].gender = c.getString("key15");
sample[i].gender = c.getString("result_status");
}
How to parse code, messge, calctime,city,id,country, name from following
use this URL : http://openweathermap.org/data/2.1/forecast/city/524901
{ "cod":"200","message":"kf","calctime":0.0342,"url":"http:\/\/openweathermap.org\/city\/524901",
"city":
{
"id":524901,
"coord":
{
"lon":37.615555,"lat":55.75222
},
"country":"RU","name":"Moscow","dt_calc":1356948005,"stations_count":6
},
Follow the below code:
JSONObject jObj=new JSONObject(jsonResponse);
String msg=jObj.getString("message");
String calctime=jObj.getString("calctime");
Use below code for parse code, messge, calctime,city,id,country, name from above url, it will solve your problem.
JSONObject mJsonObj = new JSONObject(mJsonResponse);
String mCode = mJsonObj.getString("cod");
String mMessage = mJsonObj.getString("message");
String mCalcTime = mJsonObj.getString("calctime");
JSONObject mJsonCityObj = mJsonObj.getJSONObject("city");
String mId = mJsonCityObj.getString("id");
String mConuntry = mJsonCityObj.getString("country");
String mName = mJsonCityObj.getString("name");
I have a JSON string such as below. That comes from a Website (the URL outputs below to a page) which I'm using in an android application.
{"posts": [{"id":"0000001","longitude":"50.722","latitude":"-1.87817","position":"Someplace 1","altitude":"36","description":"Some place 1 "},{"id":"0000002","longitude":"50.722","latitude":"-1.87817","position":"Some PLace 2","altitude":"36","description":"Some place 2 description"}]}
I would like to deserialize this into a List where I can iterate through them later on the application. How do I do this? I have created a class with properties and methods and a List class as below and then using fromJson to deserialize it, but it returns NULL. Hope the question is clear and many thanks in advance.
ListClass
package dataaccess;
import java.util.List;
public class LocationList {
public static List<Location> listLocations;
public void setLocationList(List <Location> listLocations) {
LocationList.listLocations = listLocations;
}
public List<Location> getLocationList() {
return listLocations;
}
}
GSON
public LocationList[] getJsonFromGson(String jsonURL) throws IOException{
URL url = new URL(jsonURL);
String content = IOUtils.toString(new InputStreamReader(url.openStream()));
LocationList[] locations = new Gson().fromJson(content, LocationList[].class);
return locations;
}
You try to deserialize into an array of LocationList objects - that surely wasn't your intent, was it? The json snippet doesn't contain a list of lists.
I would drop the class LocationList (except it ought to be extened in future?), and use a pure List. Then, you have to create a type token like this:
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<ArrayList<Location>>() {}.getType();
List<Location> locations = new Gson().fromJson(content, type);
What if this JSON response can be parsed using native classes, here is a solution for the same:
String strJsonResponse="Store response here";
JsonObject obj = new JsonObject(strJsonResponse);
JsonArray array = obj.getJsonArray("posts");
for(int i=0; i<array.length; i++)
{
JsonObject subObj = array.getJsonObject(i);
String id = subObj.getString("id");
String longitude = subObj.getString("longitude");
String latitude = subObj.getString("latitude");
String position = subObj.getString("position");
String altitude = subObj.getString("altitude");
String description = subObj.getString("description");
// do whatever procedure you want to do here
}