Android json processing - android

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.

Related

why can't I parsing value 'fields' in my code?

When I run my app, In logcat, "Problem parsing the earthquake Json results
org.json.JSONException: No value for fields"
Could you check my JSON code..? I'm beginner of JSON Parsing, So I searched a lot inf But I'm not sure about my code.
public class Utils {
private static List<News> extractFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject response = baseJsonResponse.getJSONObject("response");
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentNews = jsonArray.getJSONObject(i);
JSONObject fields = currentNews.getJSONObject("fields");
Drawable thumbnail = LoadImageFromUrl (fields.getString("thumbnail"));
String section = currentNews.getString("sectionName");
String title = currentNews.getString("webTitle");
String url = currentNews.getString("webUrl");
String date = currentNews.getString("webPublicationDate");
news.add(new News( section, title, url, date,thumbnail));
}
return news;
} catch (JSONException e) {
Log.e("Utils", "Problem parsing the news Json results", e);
}
return null;
}
private static Drawable LoadImageFromUrl(String imageurl) {
Drawable drawable = null;
InputStream inputStream = null;
try {
inputStream = new URL(imageurl).openStream();
drawable = Drawable.createFromStream(inputStream, null);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return drawable;
}
}
Try this to validate
Problem occur may be you dont have a field jsonobject in your json list. It may be not present in the some of other jsonobjects. So check if jsonobject has actual field jsonobject before parsing.
Use this condition whenever your json value might give null sometimes.
if(currentNews.has("fields"))
{
JSONObject fields = currentNews.getJSONObject("fields");
}
else
{
Log.d("JSON_TAG","NO FIELD JSON OBJECT");
}

How do I get a list of Countries, States and Cities from this JSON?

I have a JSON that contains the names of Countries, their states and cities of those states. Here is the json.
I am able to get all the countries but I can't figure out how to get the states based on the selected country and then cities based on the selected state.
Here is how I got the countries.enter code here
First to load the file from assets:
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("Contries.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Then to load the countries into an ArrayList.
public void loadCountries(String parent, String child, ArrayList<String> listValue)
{
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray(parent);;
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
// listValue = new ArrayList<>();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
listValue.add(jo_inside.getString(child));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Then this line finally:
loadCountries("Countries", "CountryName", countries);
After I have selected a country, I want to load its states. maybe something like this:
loadCountries("Pakistan", "StateName", states);
and then:
loadCountries("Islamabad Capital Territory", "CityName", cities);
Any help is greatly appreciated.
Working with JSON can be error-prone. Why don't we model objects around your data and we can do something a little more clearer.
Overview.
Lets' Model your objects
Let's Deserialize your raw json into "Objects"
Then we can "query" our modelled objects!
Step 1 - Modelling.
Note I'm not including constructors, getters, setters and any other boiler plate.
public class Country {
private List<State> states;
private String name;
public Optional<State> getStateByName(String name) {
return States.stream().filter(state -> state.getName().equals(name)).findFirst();
}
}
public class State {
private List<String> cities;
private String name;
public Optional<String> getCityByName(String name) {
return cities.stream().filter(city -> city.equals(name)).findFirst();
}
}
public class CountryDataProvider {
private List<Country> countries;
public CountryDataProvider(String rawData) {
// parse your json to create a List of object Country (tip: Use something like Jackson or Gson to do this for you).
// Ref to part 2
}
public Optional<Country> getCountryByName(String name) {
return countries.stream().filter(country -> country.getName().equals(name)).findFirst();
}
}
Step 2 - Deserialize.
This is a broad topic and To be honest there is a lot of libraries that will do it better and they are really easy to add to your project. Here are a few:
Jackson https://github.com/FasterXML/jackson
GSON https://github.com/google/gson <- My pick.
Step 3 - Query
From here you can do what ever you want
countryData = new CountryDataProvider(data);
Optional<List<String>> countriesInPunjab = countryData.getCountryByName("Pakistan")
.map(country -> country.getStateByName("Punjab")
.map(state -> state.getCities()); // would give you all the cities in Punjab, Pakistan.
The code I have given in my example does use functional and Optional interfaces (in Java 8). Let me know if you want them rewritten in a less functional way.
Here is another solution, not very CPU friendly but it works:
First use this method to get a list of countries:
public void loadCountries(String parent, String child, ArrayList<String> listValue)
{
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray(parent);
// m_jArry;
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
// listValue = new ArrayList<>();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
listValue.add(jo_inside.getString(child));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Call this method like this:
loadCountries("Countries", "CountryName", countries);
Then use the following method to load the States and Cities.
private void getCitiesByState(String countryName, String stateName)
{
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray countriesArray = json.getJSONArray("Countries");
for(int i = 0; i < countriesArray.length(); i++)
{
JSONObject countryJSON = countriesArray.getJSONObject(i);
if(countryJSON.getString("CountryName").equals(countryName))
{
JSONArray statesArray = countryJSON.getJSONArray("States");
states.clear();
for(int j = 0; j < statesArray.length(); j++)
{
JSONObject statesJSON = statesArray.getJSONObject(j);
states.add(statesJSON.getString("StateName"));
if(statesJSON.getString("StateName").equals(stateName))
{
JSONArray citiesarray = statesJSON.getJSONArray("Cities");
cities.clear();
for(int k = 0; k < citiesarray.length(); k++)
{
cities.add(citiesarray.getString(k));
}
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

How do I convert an object that contains and arraylist of other objects into JSON for sending to an API - Android

Imagine I have an object - ChildObject. ChildObject has 3 properties. Id, Name, Age.
I also have another object - ParentObject. ParentObject also has 3 properties. Id, Date but the 3rd is ArrayList of ChildObjects Family.
How would I go about converting this into a JSONObject to be able to send it over to a RESTfull WebAPI service.
So far I have failed to find anything that works, and I'm struggling to wrap my head around the problem.
To make it more of a challenge I cant use 3rd party extentions (eg gson etc).
Thanks in advance for your help.
Adding Objects to see if they make it any clearer
ParentObject
public class JobMovementRequestDto {
public String Id_Employee;
public String ActionDate;
public String Id_Terminal;
public String Id_Device;
public ArrayList<JobActivityRequestDto> FromJobs;
public ArrayList<JobActivityRequestDto> ToJobs;
public JobMovementRequestDto(){
}
public JobMovementRequestDto(String idEmployee, String activityDate, String idTerminal, String idDevice, ArrayList<JobActivityRequestDto> fromItems, ArrayList<JobActivityRequestDto> toItems){
this.Id_Employee = idEmployee;
this.ActionDate = activityDate;
this.Id_Terminal = idTerminal;
this.Id_Device = idDevice;
this.FromJobs = fromItems;
this.ToJobs = toItems;
}
public String getIdEmployee() {return this.Id_Employee;}
public String getActivityDate() {return this.ActionDate;}
public String getIdTerminal() {return this.Id_Terminal;}
public String getIdDevice() {return this.Id_Device;}
public ArrayList<JobActivityRequestDto> getFromList() {return this.FromJobs;}
public ArrayList<JobActivityRequestDto> getToLIst() { return this.ToJobs;}
ChildObject
public class JobActivityRequestDto {
public String Id_Job;
public String Id_Batch;
public String Id_ActivityType;
public JobActivityRequestDto()
{
}
public JobActivityRequestDto(String idJob, String idBatch, String idActivityType)
{
this.Id_Job = idJob;
this.Id_Batch = idBatch;
this.Id_ActivityType = idActivityType;
}
public String getIdJob() { return this.Id_Job;}
public String getIdBatch() {return this.Id_Batch;}
public String getIdActivityType() {return this.Id_ActivityType;}
}
Here is your complete solution, Please check.
public void makeJsonObject()
{
try
{
JSONObject parentJsonObject = new JSONObject();
parentJsonObject.put("Id", parentObject.getId());
parentJsonObject.put("Id", parentObject.getDate());
JSONArray childListArr = new JSONArray();
for (int i = 0; i < parentObject.ChildObjectsList().size(); i++)
{
ChildObject childObject = parentObject.ChildObjectsList().get(i);
JSONObject childJsonObject = new JSONObject();
childJsonObject.put("id", childObject.getId());
childJsonObject.put("Name", childObject.getName());
childJsonObject.put("Age", childObject.getAge());
childListArr.put(childJsonObject);
}
parentJsonObject.put("childList", childListArr);
Log.e(TAG, "parentJsonObject=="+parentJsonObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
JSONObject fromObject, toObject, parentObject;
JSONArray fromArray, toArray;
JobMovementRequestDto JMRD = new JobMovementRequestDto();
try {
parentObject = new JSONObject();
parentObject.put("Id_Employee", JMRD.getIdEmployee());
parentObject.put("ActionDate", JMRD.getActivityDate());
parentObject.put("Id_Terminal", JMRD.getIdTerminal());
parentObject.put("Id_Device", JMRD.getIdDevice());
fromArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getFromList()){
//Loop your multiple childObjects and add it childArray
fromObject = new JSONObject();
fromObject.put("Id_Job",JARD.getIdJob());
fromObject.put("Id_Batch",JARD.getIdBatch());
fromObject.put("Id_ActivityType",JARD.getIdActivityType());
fromArray.put(fromObject);
}
toArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getToLIst()){
//Loop your multiple childObjects and add it childArray
toObject = new JSONObject();
toObject.put("Id_Job",JARD.getIdJob());
toObject.put("Id_Batch",JARD.getIdBatch());
toObject.put("Id_ActivityType",JARD.getIdActivityType());
toArray.put(toObject);
}
//Finally, Add childArray to ParentObject.
parentObject.put("fromObjects",fromArray);
parentObject.put("toObjects",toArray);
} catch (JSONException e) {
e.printStackTrace();
}
Create a JSON like this and You Can Send This to Your Server. I Hope This Is What You Want Right?

parse complex json in android

i have this json:
[{"id":"1","name":"john"},{"id":"2","name":"jack"},{"id":"3","name":"terry"}]
how i can parse this? i have to use a loop for extracting each group? for simple jsons i use this code:
public static String parseJSONResponse(String jsonResponse) {
try {
JSONObject json = new JSONObject(jsonResponse);
// get name & id here
String name = json.getString("name");
String id = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
but now i have to parse my new json. please help me
It should be like this:
public static String parseJSONResponse(String jsonResponse) {
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
for (int index = 0; index < jsonArray.length(); index++) {
JSONObject json = jsonArray.getJSONObject(index);
// get name & id here
String name = json.getString("name");
String id = json.getString("id");
}
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
Of course you should return an array of names or whatever you want..
This is meant to be parsed by a JSONArray, and then each "record" is a JSONObject.
You can loop on the array and then retrieve the JSON String of each record with the getString(int) method. Then use this string to build a JSONObject, and just extract values like you do now.
You can use the following code:
public static void parseJSONResponse(String jsonResponse) {
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
if(jsonArray != null){
for(int i=0; i<jsonArray.length(); i++){
JSONObject json = jsonArray.getJSONObject(i);
String name = json.getString("name");
String id = json.getString("id");
//Store strings data or use it
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
You need to modify the loop to store or use the data.
Hope it helps.

parse json in android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON Parsing in Android
As I find out I need to use Gson class to parse json to Java object in android. It's quite easy to parse simple varables or array, but I don't know how to parse more complex json string, my json look like this:
{"selected_id":3, "data":[{"id":"3","score":"1534"},{"id":"1","score":"1234"}]}
Can anyone help me how to do this?
//Model class
class Model {
private String mId ;
private String mScore;
public Model (String id , String score){
mId = id ;
mScore= score
}
//getter and setter
}
// in your class
private ArrayLsit getLsit(String str){
ArrayLsit<Model > list = new ArrayLsit<Model>();
// getting JSON string from URL
JSONObject json = new JSONObject(str);
try {
// Getting Array of Contacts
contacts = json.getJSONArray("data");
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("id");
String score= c.getString("score");
list.add(new Model(id ,score))
}
} catch (JSONException e) {
e.printStackTrace();
}
return list
}
Check out the code..
Result = jsonObject.getString("data");
jsonArray = new JSONArray(Result);
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
try {
jsonObject.getString("Id");
} catch (Exception ex) {
cafeandbarsList.add(null);
ex.printStackTrace();
}
}
Thanks
create to class for json,
Gson gson = new Gson();
Jsondata jsonddata = gson.fromJson(response, Jsondata .class);
=====
JsonData.jave
#SerializedName("selected_id")
public String sid;
#SerializedName("data")
public List<data> dalalist;
===
data.java
#SerializedName("id")
public String id;
#SerializedName("score")
public String score;

Categories

Resources