Parsing some array from json and some items in it in android - android

i want to parse userinfo Array and some string in it. and getuserlistdata array and some string in it. please help me how to parse this response.This is my respons.
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test",
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India"
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
},
],
]
}
}
Sir, This my code.
protected Void doInBackground(Void...arg0) {
// Creating service handler class instance
ServiceHandler2 sh = new ServiceHandler2();
String url_links = "http://192.168.0.65/hostandguest/android/viewprofile?uid=77";
Log.d("url_links: ", "> " + url_links);
String jsonStr = sh.makeServiceCall(url_links, ServiceHandler2.GET);
Log.v("Profile:", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
status = obj.getString("status");
data = obj.getString("data");
if (status.equalsIgnoreCase("false")) {
} else {
jsonarr = obj.getJSONArray("userinfo");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject c = jsonarr.getJSONObject(i);
String fname = c.getString("firstname");
Datein_arr.add(fname);
String id = c.getString("id");
}
jsonarr2 = obj.getJSONArray("getuserlistdata");
for (int j = 0; j < jsonarr2.length(); j++) {
JSONObject jo = jsonarr2.getJSONObject(j);
address = jo.getString("address");
Log.v("address", "" + address);
Log.v("Profile:", "777777777777777777777777777777777777");
hostimgrr2 = obj.getJSONArray("hostImage");
if (hostimgrr2.length() == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
det_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
} else {
for (int k = 0; k < hostimgrr2.length(); k++) {
JSONObject js = hostimgrr2.getJSONObject(k);
img = js.getString("images");
Log.v("img", "" + img);
if (k == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Try like below code to parse JSONArray.
try {
private ArrayList<UserInfo> userInfoList = new ArrayList<UserInfo>();
JSONObject jsonObject = new JSONObject(jsonData); // jsonData is your reponse string
JSONArray userinfo = jsonData.getJSONArray("userinfo");
for(int i = 0; i < userinfo.length(); i++) {
JSONObject jObject = userinfo.getJSONObject(i);
UserInfo userInfo = new UserInfo();
userInfo.setId( jObject.getString("id") );
userInfo.setFirstname( jObject.getString("firstname") );
userInfoList.add(userInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
UserInfo class as follow.
public class UserInfo {
public String id = "";
public String firstname = "";
public String getID() {
return coursePrice;
}
public void setID(String id) {
this.id = id;
}
public String getFirstname() {
return coursePrice;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}

First you have to validate your jsondata.
You can goto JSONLint to check whether your json is valid or not
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test"
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India",
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
}
]
}
]
}
}
And You are parsing a JSONObject as String.
ie, it should be obj.getJSONObject("data"); instead of obj.getString("data");
Also check for other parsing issues like this.

Related

JSON mistmatching Key and value -difficult to parse in Kotlin

I have the following json
[
{
"abc": "",
"type": "string"
},
{
"bcd": "",
"type": "dropdown"
},
{
"efg": "",
"type": "dropdown"
},
{
"hij": "",
"type": "string"
},
{
"klm": "",
"type": "string"
}
]
I am facing difficulties in parsing the json in Kotlin.
How can i parse this JSON from Retrofit API - Kotlin Suspend Function?
You can parse this json using mentioned function :
private void parseDynamicJson(JSONObject data) {
if (data != null) {
Iterator<String> keys = data.keys();
while (keys.hasNext()) {
String key = keys.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray dataJSONArray = data.getJSONArray(key);
int size = dataJSONArray.length();
for (int i = 0; i < size; i++) {
parseDynamicJson(dataJSONArray.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseDynamicJson(data.getJSONObject(key));
} else {
System.out.println("parseDynamicJson" + key + ":" + data.getString(key));
}
} catch (Exception e) {
try {
System.out.println("parseDynamicJson" + key + ":" + data.getString(key));
} catch (Exception ee) {
ee.printStackTrace();
}
e.printStackTrace();
}
}
}
}

How to filter the recyclerlistview in android

Hi in the code I am using recyclerview to displaying a listview .I am calling the APi and rending the list .But in that list contains data are chnaging with the content.
I want to filter the list and display it into single list item
For example list items contains name and details and unique no.want to display all the contents are name
sample json response:
"blocks": [
{
"label": "Basic Information",
"fields": [
{
"name": "sales_stage",
"value": "Opportunity",
"label": "Sales Stage",
"uitype": "15",
"type": {
"defaultValue": null
}
},
{
"name": "potentialname",
"value": "GVN hospital-Falco",
"label": "Opportunity Name",
"uitype": "2",
"type": {
"defaultValue": null
}
},
{
"name": "assigned_user_id",
"value": {
"value": "19x84",
"label": "Chandra Mouli N"
},
"label": "Assigned To",
"uitype": "53",
"type": {
"defaultValue": {
"value": "19x1",
"label": "Administrator"
}
}
},
{
"name": "potential_no",
"value": "GW/OPP/100743",
"label": "Opportunity Number",
"uitype": "4",
"type": {
"defaultValue": null
}
}
{"label": "Products",
"fields": [
{
"name": "productid",
"value": {
"value": "14x33080",
"label": "CS 30"
},
"label": "Item Name",
"uitype": "10",
"type": {
"defaultValue": null
}
},]
}
]
}]
"blocks": [
{
"label": "Basic Information",
"fields": [
{
"name": "sales_stage",
"value": "Opportunity",
"label": "Sales Stage",
"uitype": "15",
"type": {
"defaultValue": null
}
},
{
"name": "potentialname",
"value": "GVN hospital-Falco",
"label": "Opportunity Name",
"uitype": "2",
"type": {
"defaultValue": null
}
},
{
"name": "assigned_user_id",
"value": {
"value": "19x84",
"label": "Chandra Mouli N"
},
"label": "Assigned To",
"uitype": "53",
"type": {
"defaultValue": {
"value": "19x1",
"label": "Administrator"
}
}
},
{
"name": "potential_no",
"value": "GW/OPP/100743",
"label": "Opportunity Number",
"uitype": "4",
"type": {
"defaultValue": null
}
}]
{"label": "Products",
"fields": [
{
"name": "productid",
"value": {
"value": "14x33080",
"label": "CS 30"
},
"label": "Item Name",
"uitype": "10",
"type": {
"defaultValue": null
}
},]
}]
Actual output:
example: list1:
name :xyz
product:123
list2:
name :xyz
product:abc
list3:
name :xyz
product:1234
Expected output:
list:
name :xyz
product:123,abc,1234
Java:
private void fetchJSONForSales(){
handler.postDelayed(new Runnable() {
#Override
public void run() {
sessionId = getActivity().getIntent().getStringExtra("sessionId");
String operation = "syncModuleRecords";
String module = "Potentials";
String syncToken="";
String mode="public";
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<SyncModule> call = service.GetSyncModuleList(operation, sessionId, module,syncToken,mode);
/**Log the URL called*/
Log.i("URL Called", call.request().url() + "");
call.enqueue(new Callback<SyncModule>() {
#Override
public void onResponse(Call<SyncModule> call, Response<SyncModule> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
SyncModule syncModule = response.body();
String success = syncModule.getSuccess();
if (success.equals("true")) {
SyncResults results = syncModule.getResult();
Sync sync=results.getSync();
ArrayList<SyncUpdated> syncUpdateds=sync.getUpdated();
for(SyncUpdated syncUpdated:syncUpdateds){
ArrayList<SyncBlocks> syncBlocks=syncUpdated.getBlocks();
String title = "";
String value = "";
String potentialValue = "";
String potentialNo = "";
String assigned = "";
String contact = "";
String location = "";
String related = "";
String winprobValue = "";
String valueAndQty = "";
String productValue = "";
String quantity = "";
String salesstageValue="";
String employee="";
String leadsource="";
String remark_sales_person="";
String segment="";
String modality="";
String circle="";
String prospect_type="",equ_details="",sale_type="",createdtime="",modifiedtime="",modifiedby="",closingdate="",exp_delivery_date="",pndt="",demo_done="",s_i="",demo_date="",fun_req="",site_read="",
support_person="",support_type="",opportunity_type="",department="",rating="",interest_type="",
txt_adj="",hdnS_H_Amount="",pre_tax_total="",hdnSubTotal="",listprice="",comment="",discount_amount="",tax1="",tax2="",tax3="",lost_reason="",
competition_name="",price_quoted="",general_remark="",description="",termsnconditions="";
String mobie = sharedPreferences.getString("mobiles", null);
for (SyncBlocks syncBlocks1 : syncBlocks) {
String label = syncBlocks1.getLabel();
//Basic Information
if (label.equals("Basic Information")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
String name = synFields1.getName();
values = synFields1.getValue();
if (name.equals("sales_stage")) {
salesstageValue = String.valueOf(values);
} else if (name.equals("potentialname")) {
potentialValue = String.valueOf(values);
} else if (name.equals("assigned_user_id")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
// assigned_tos.add(v);
assigned = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
} else if (name.equals("related_to")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
// assigned_tos.add(v);
related = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
} else if (name.equals("contact_id")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
contact = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
} else if (name.equals("potential_no")) {
potentialNo = String.valueOf(values);
} else if (name.equals("location")) {
location = String.valueOf(values);
}else if (name.equals("employee")) {
employee = String.valueOf(values);
}else if (name.equals("leadsource")) {
leadsource = String.valueOf(values);
}else if (name.equals("cf_954")) {
remark_sales_person = String.valueOf(values);
}else if (name.equals("segment")) {
segment = String.valueOf(values);
}else if (name.equals("modality")) {
modality = String.valueOf(values);
}else if (name.equals("circle")) {
circle = String.valueOf(values);
}
}
} else if (label.equals("Opportunity Details")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
String name = synFields1.getName();
values = synFields1.getValue();
if (name.equals("cf_996")) {
title = String.valueOf(values);
} else if (name.equals("cf_897")) {
winprobValue = String.valueOf(values);
}else if (name.equals("cf_960")) {
prospect_type = String.valueOf(values);
}else if (name.equals("cf_1010")) {
equ_details = String.valueOf(values);
}else if (name.equals("cf_992")) {
sale_type = String.valueOf(values);
}else if (name.equals("createdtime")) {
createdtime = String.valueOf(values);
}else if (name.equals("modifiedtime")) {
modifiedtime = String.valueOf(values);
} else if (name.equals("modifiedby")) {
try {
Gson gson = new Gson();
String strJson = gson.toJson(values);
JSONObject jsonObject = new JSONObject(strJson);
String v = jsonObject.getString("label");
modifiedby = v;
} catch (Exception ex) {
Log.e("SalesStageFragment", "Exception is : " + ex.toString());
}
}else if (name.equals("closingdate")) {
closingdate = String.valueOf(values);
}else if (name.equals("cf_1000")) {
exp_delivery_date = String.valueOf(values);
}else if (name.equals("cf_998")) {
pndt = String.valueOf(values);
}else if (name.equals("demo_done")) {
demo_done = String.valueOf(values);
}else if (name.equals("cf_903")) {
s_i = String.valueOf(values);
}else if (name.equals("demo_date")) {
demo_date = String.valueOf(values);
}else if (name.equals("cf_899")) {
fun_req = String.valueOf(values);
}else if (name.equals("cf_1002")) {
site_read = String.valueOf(values);
}else if (name.equals("cf_1004")) {
support_person = String.valueOf(values);
}else if (name.equals("cf_1006")) {
support_type = String.valueOf(values);
}else if (name.equals("opportunity_type")) {
opportunity_type = String.valueOf(values);
}
}
}
}
String rupee = getResources().getString(R.string.Rs);
int paswd = (int) Double.parseDouble(quantity);
String qty=String.valueOf(paswd);
ModelTest modelTest = new ModelTest(potentialValue,related,assigned,contact,location,productValue,rupee.concat(valueAndQty),
potentialNo,mobie,competition_name,circle,closingdate,comment,createdtime,demo_date,demo_done,department
,description,discount_amount,equ_details,employee,exp_delivery_date,fun_req,general_remark,hdnS_H_Amount,hdnSubTotal,
interest_type,lost_reason,leadsource,listprice,modality,modifiedby,modifiedtime,opportunity_type,pre_tax_total,pndt,price_quoted,prospect_type,
rating,remark_sales_person,sale_type,support_type,s_i,segment,site_read,txt_adj,tax1,tax2,tax3,termsnconditions,winprobValue,support_person,qty,salesstageValue);
if(salesstageValue.equals("Opportunity")){
listSalesStageOpportunity.add(modelTest);
opportunityAdapter.notifyDataSetChanged();
As you are passing the complete model class i.e "modelTest object" to the adapter by adding it to "listSalesStageOpportunity list". All you have to change is your layout. Inflate the recycler view for item containing the names only that you want to show. If you are creating different textviews in recycler view for each data then you just need to setVisibility to View.VISIBLE for names only or you can do so by declaring it in XML layout.
HI you need to add the check there where do you want to select the name
if("name").equals.("xyz"){
append("data yo want to append")
}

JSON Parsing data from 2 dimension array

I need to get data from house array, My json file looks like,
{
"mydata": {
"totalRoads": "13",
"noOfHouse": "5",
"house": [
{
"road": "1",
"right": [
{
"houseID": "A3",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A4",
"isPainted": "true",
"ownerGender": "female"
}
],
"left": [
{
"houseID": "A1",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A2",
"isPainted": "false",
"ownerGender": "female"
}
]
},
{
"road": "2",
"right": [
{
"houseID": "B3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "B4",
"isPainted": "true",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "B1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "B2",
"isPainted": "true",
"ownerGender": "male"
}
]
},
{
"road": "3",
"right": [
{
"houseID": "C3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "C4",
"isPainted": "false",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "C1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "C2",
"isPainted": "false",
"ownerGender": "male"
}
]
}
]
}
}
I just tried like this to parse data from json,
InputStream inputStream = getResources().openRawResource(R.raw.house_details);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("House Data", byteArrayOutputStream.toString());
try {
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray jArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
house_ID = jArray.getJSONObject(i).getString("houseID");
is_painted = jArray.getJSONObject(i).getBoolean("isPainted");
owner_gender = jArray.getJSONObject(i).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted), owner_gender });
}
} catch (Exception e) {
e.printStackTrace();
}
But I couldn't get what I am expecting, Please help me get all data from json.
You can use Gson lib to get the data from Json easy way and your structure will be like this
public class Response{
#SerializedName("mydata")
private Mydata mydata;
public void setMydata(Mydata mydata){
this.mydata = mydata;
}
public Mydata getMydata(){
return mydata;
}
#Override
public String toString(){
return
"Response{" +
"mydata = '" + mydata + '\'' +
"}";
}
}
public class Mydata{
#SerializedName("totalRoads")
private String totalRoads;
#SerializedName("noOfHouse")
private String noOfHouse;
#SerializedName("house")
private List<HouseItem> house;
public void setTotalRoads(String totalRoads){
this.totalRoads = totalRoads;
}
public String getTotalRoads(){
return totalRoads;
}
public void setNoOfHouse(String noOfHouse){
this.noOfHouse = noOfHouse;
}
public String getNoOfHouse(){
return noOfHouse;
}
public void setHouse(List<HouseItem> house){
this.house = house;
}
public List<HouseItem> getHouse(){
return house;
}
#Override
public String toString(){
return
"Mydata{" +
"totalRoads = '" + totalRoads + '\'' +
",noOfHouse = '" + noOfHouse + '\'' +
",house = '" + house + '\'' +
"}";
}
}
public class HouseItem{
#SerializedName("road")
private String road;
#SerializedName("left")
private List<LeftItem> left;
#SerializedName("right")
private List<RightItem> right;
public void setRoad(String road){
this.road = road;
}
public String getRoad(){
return road;
}
public void setLeft(List<LeftItem> left){
this.left = left;
}
public List<LeftItem> getLeft(){
return left;
}
public void setRight(List<RightItem> right){
this.right = right;
}
public List<RightItem> getRight(){
return right;
}
#Override
public String toString(){
return
"HouseItem{" +
"road = '" + road + '\'' +
",left = '" + left + '\'' +
",right = '" + right + '\'' +
"}";
}
}
Hi your json is not valid one
{
"mydata": {
"totalRoads": "13",
"noOfHouse": "5",
"house": [
{
"road": "1",
"right": [
{
"houseID": "A3",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A4",
"isPainted": "true",
"ownerGender": "female"
}
],
"left": [
{
"houseID": "A1",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A2",
"isPainted": "false",
"ownerGender": "female"
}
]
},
{
"road": "2",
"right": [
{
"houseID": "B3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "B4",
"isPainted": "true",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "B1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "B2",
"isPainted": "true",
"ownerGender": "male"
}
]
},
{
"road": "3",
"right": [
{
"houseID": "C3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "C4",
"isPainted": "false",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "C1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "C2",
"isPainted": "false",
"ownerGender": "male"
}
]
}
]
}
}
try {
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray jArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj= jArray.getJSONObject(i);
JSONArray right = obj.getJSONArray("right");
JSONArray left= obj.getJSONArray("left");
for(int j=0;j<right.length();j++)
{
house_ID = right.getJSONObject(j).getString("houseID");
is_painted = right.getJSONObject(j).getBoolean("isPainted");
owner_gender = right.getJSONObject(j).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted),
owner_gender });
}
for(int j=0;j<left.length();j++)
{
house_ID = left.getJSONObject(j).getString("houseID");
is_painted = left.getJSONObject(j).getBoolean("isPainted");
owner_gender = left.getJSONObject(j).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted),
owner_gender });
}
}
} catch (Exception e) {
e.printStackTrace();
}
1- Create a model for houseData i.e.
public class HotelEntity {
private String houseID;
private String isPainted;
private String ownerGender;
// add getter and setter here
}
2- Parse data from right and left from each house object
for (int i = 0; i < jArray.length(); i++) {
//get the data and map it object
Array.getJSONObject(i).getString("right");
for {
// add all models to list
}
Array.getJSONObject(i).getString("left");
for {
// add all models to list
}
}
3 Add it in ArrayList of your houseEntity.
Also, you can use Gson for the json to object conversion.
You don't have to manually parse data from json.
You can create object from your json String with
http://www.jsonschema2pojo.org/
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("mydata")
#Expose
private Mydata mydata;
public Mydata getMydata() {
return mydata;
}
public void setMydata(Mydata mydata) {
this.mydata = mydata;
}
}
-----------------------------------com.example.House.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class House {
#SerializedName("road")
#Expose
private String road;
#SerializedName("right")
#Expose
private List<Right> right = null;
#SerializedName("left")
#Expose
private List<Left> left = null;
public String getRoad() {
return road;
}
public void setRoad(String road) {
this.road = road;
}
public List<Right> getRight() {
return right;
}
public void setRight(List<Right> right) {
this.right = right;
}
public List<Left> getLeft() {
return left;
}
public void setLeft(List<Left> left) {
this.left = left;
}
}
-----------------------------------com.example.Left.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Left {
#SerializedName("houseID")
#Expose
private String houseID;
#SerializedName("isPainted")
#Expose
private String isPainted;
#SerializedName("ownerGender")
#Expose
private String ownerGender;
public String getHouseID() {
return houseID;
}
public void setHouseID(String houseID) {
this.houseID = houseID;
}
public String getIsPainted() {
return isPainted;
}
public void setIsPainted(String isPainted) {
this.isPainted = isPainted;
}
public String getOwnerGender() {
return ownerGender;
}
public void setOwnerGender(String ownerGender) {
this.ownerGender = ownerGender;
}
}
-----------------------------------com.example.Mydata.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Mydata {
#SerializedName("totalRoads")
#Expose
private String totalRoads;
#SerializedName("noOfHouse")
#Expose
private String noOfHouse;
#SerializedName("house")
#Expose
private List<House> house = null;
public String getTotalRoads() {
return totalRoads;
}
public void setTotalRoads(String totalRoads) {
this.totalRoads = totalRoads;
}
public String getNoOfHouse() {
return noOfHouse;
}
public void setNoOfHouse(String noOfHouse) {
this.noOfHouse = noOfHouse;
}
public List<House> getHouse() {
return house;
}
public void setHouse(List<House> house) {
this.house = house;
}
}
-----------------------------------com.example.Right.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Right {
#SerializedName("houseID")
#Expose
private String houseID;
#SerializedName("isPainted")
#Expose
private String isPainted;
#SerializedName("ownerGender")
#Expose
private String ownerGender;
public String getHouseID() {
return houseID;
}
public void setHouseID(String houseID) {
this.houseID = houseID;
}
public String getIsPainted() {
return isPainted;
}
public void setIsPainted(String isPainted) {
this.isPainted = isPainted;
}
public String getOwnerGender() {
return ownerGender;
}
public void setOwnerGender(String ownerGender) {
this.ownerGender = ownerGender;
}
}
And you can get everything with:
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
Gson g = new Gson();
Example example = g.fromJson(jObject .toString(), Example.class);
You can get value from Example.
Mydata mydata = example.getMyData();
List<House> lstHouse = mydata.getHouse();
for (i= 0; i < lstHouse.size(); i++){
House house = lstHouse.get(i);
String road = house.getRoad();
List<Right> lstRight = house.getRight();
for (j= 0; j < lstRight .size(); j++){
Right right = lstRight.get(j);
String houseID = right.getHouseID();
String isPainted = right.getIsPainted();
String ownerGender = right.getOwnerGender();
}
List<Left> lstLeft = house.getLeft();
for (k= 0; k < lstLeft .size(); k++){
Left left= lstLeft .get(k);
String houseID = left.getHouseID();
String isPainted = left.getIsPainted();
String ownerGender = left.getOwnerGender();
}
}
I hope it can help your problem!
You're trying to access data from house to houseId, but you have to go through right and left structures previously.
houseID is inside the right array not in house array.
Try this :
JSONObject jObject = new JSONObject(byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray jArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObj = jArray.getJSONObject(i);
JSONArray jsonArray = jsonObj.getJSONArray("right");
for (int j = 0; j < jsonArray.length(); j++)
{
house_ID = jsonArray.getJSONObject(j).getString("houseID");
is_painted = jsonArray.getJSONObject(j).getBoolean("isPainted");
owner_gender = jsonArray.getJSONObject(j).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted), owner_gender });
}
}
Here is a solution which is very close to your implementation, however, correct, and will also read the "left" array :)
InputStream inputStream = getResources().openRawResource(R.raw.sojson);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("House Data", byteArrayOutputStream.toString());
try {
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray houseArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < houseArray.length(); i++) {
JSONObject ob = houseArray.getJSONObject(i);
JSONArray rightArray = ob.getJSONArray("right");
for (int r = 0; r < rightArray.length(); r++) {
house_ID = rightArray.getJSONObject(r).getString("houseID");
is_painted = rightArray.getJSONObject(r).getBoolean("isPainted");
owner_gender = rightArray.getJSONObject(r).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[]{house_ID, String.valueOf(is_painted), owner_gender});
}
JSONArray leftArray = ob.getJSONArray("left");
for (int l = 0; l < leftArray.length(); l++) {
house_ID = leftArray.getJSONObject(l).getString("houseID");
is_painted = leftArray.getJSONObject(l).getBoolean("isPainted");
owner_gender = leftArray.getJSONObject(l).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[]{house_ID, String.valueOf(is_painted), owner_gender});
}
}
} catch (Exception e) {
e.printStackTrace();
}
Be sure to use valid JSON:
{
"mydata":{
"totalRoads":"13",
"noOfHouse":"5",
"house":[
{
"road":"1",
"right":[
{
"houseID":"A3",
"isPainted":"false",
"ownerGender":"female"
},
{
"houseID":"A4",
"isPainted":"true",
"ownerGender":"female"
}
],
"left":[
{
"houseID":"A1",
"isPainted":"false",
"ownerGender":"female"
},
{
"houseID":"A2",
"isPainted":"false",
"ownerGender":"female"
}
]
},
{
"road":"2",
"right":[
{
"houseID":"B3",
"isPainted":"false",
"ownerGender":"male"
},
{
"houseID":"B4",
"isPainted":"true",
"ownerGender":"male"
}
],
"left":[
{
"houseID":"B1",
"isPainted":"true",
"ownerGender":"male"
},
{
"houseID":"B2",
"isPainted":"true",
"ownerGender":"male"
}
]
},
{
"road":"3",
"right":[
{
"houseID":"C3",
"isPainted":"false",
"ownerGender":"male"
},
{
"houseID":"C4",
"isPainted":"false",
"ownerGender":"male"
}
],
"left":[
{
"houseID":"C1",
"isPainted":"true",
"ownerGender":"male"
},
{
"houseID":"C2",
"isPainted":"false",
"ownerGender":"male"
}
]
}
]
}
}
house_ID = jArray.getJSONObject(i).getString("houseID"); // WRONG WAY
I guess JSONException will occur.
You should create two FOR loop.
for (int i = 0; i < jArray.length(); i++)
{
JSONObject _jOBJ = jArray.getJSONObject(i);
JSONArray jsonArray = _jOBJ.getJSONArray("right");
for (int j = 0; j < jsonArray.length(); j++)
{
JSONObject _jOBJCHILD = jsonArray.getJSONObject(j);
String str_HOUSEID = _jOBJCHILD.getString("houseID");
}
}

After Getting object/array from json, how can i shuffle it (Randomize)

I got the json data using this
``
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList() {
return quesList;
}
``
Here is the json data.
``
{
"Questions": [
{
"Question": "Which animal is Carnivorous?",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Cow"
},
{
"Answer": "Lion"
},
{
"Answer": "Goat"
},
{
"Answer": "Elephant"
}
]
},
{
"Question": "Humans need",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Oxygen"
},
{
"Answer": "Nitrogen"
},
{
"Answer": "CarbonDioxide"
},
{
"Answer": "Hydrogen"
}
]
},
{
"Question": "Choose the Amphibian ",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Frog"
},
{
"Answer": "Owl"
},
{
"Answer": "Goat"
},
{
"Answer": "Fox"
}
]
},
{
"Question": "---- is part of Earth`s Atmosphere.",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Unisphere"
},
{
"Answer": "Troposphere"
},
{
"Answer": "Oxysphere"
},
{
"Answer": "Carbosphere"
}
]
},
]
}
After getting the json data
All I need now is to randomize it.
Help a brother please, I have tried everything but nothing is working
Thanks in advance
After
quesList = quesObj.getJSONArray("Questions"); // Right place to shuffle PeterOla,add this to randomize questions list:
List<JSONObject> questionsList = new ArrayList<JSONObject>(quesList.length());
for(int i=0,size=quesList.length();i<size;++i){
try {
questionsList.add(quesList.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
long seed = System.nanoTime();
Collections.shuffle(questionsList, new Random(seed));
Put values into a list, then you can shuffle it easily. Use this:
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
Collections.shuffle(listdata);
try {
JSONObject jsonObject = new JSONObject(response);
String current_page = jsonObject.optString("current_page");
NextPageUrl = jsonObject.optString("next_page_url");
if (current_page.equals("1")){
lifeHomeModels.clear();
JSONArray data = jsonObject.getJSONArray("data");
for (int i =0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
String id = jsonObject1.optString("id");
String post_user_id = jsonObject1.optString("user_id");
String post_id = jsonObject1.optString("post_id");
String post_details = jsonObject1.optString("post_details");
}
Family_HomeModel inputModel = new Family_HomeModel();
inputModel.setId(id);
inputModel.setPost_user_id(post_user_id);
inputModel.setPost_id(post_id);
inputModel.setPost_details(post_details);
lifeHomeModels.add(inputModel);
}
long seed = System.nanoTime();
Collections.shuffle(lifeHomeModels, new Random(seed));
}
lifeHomeAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}

How to select only particular values from bunch of JSON response?

I want to get only some selected values from the JSON response.For example if JSON contains 100 string values then i need to take the values which are starting with # symbol from that 100 values.
How can I do that ?
Following is my JSON,
[{"Obj" :
{ "ID":"11",
"NAME":"XYZ",
"GENDER":"M"
}
{ "ID":"11",
"NAME":"#XYZ",
"GENDER":"M"
}
{ "ID":"11",
"NAME":"#XYZ",
"GENDER":"M"
}
}]
Here I need to fetch Name which having # symbol
You can use below method to get the Name which start with # :
JSONObject jsonObject = new JSONObject(response);// u can change it as per your need
JSONArray jArray = jsonObject.getJSONArray("Obj");// if your `Obj` is an JsonArray
for (int i = 0; i < jArray.length(); i++) {
String json_name = jArray.getJSONObject(i).getString("NAME");
if(json_name.startsWith("#"))
{
Log.d(TAG,"It start with #");
}
}
Try out as below:
private void parseJSON(String json) {
try {
JSONArray items = new JSONArray(<your Json Response>);
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
System.err.println("Object---" + item.getString("Obj"));
JSONObject obj=item.getJSONObject("Obj");
for (int j = 0; j < obj.length(); j++) {
String Name=obj.getString("NAME");
if(obj.getString("NAME").toString().contains("#"))
{
Log.d("Name starts with-->", Name);
}
else
{
Log.d("Name does not start with-->", Name);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try this.
first of all that's not a valid json may be below json is correct format
[
{
"Obj": [
{
"ID": "11",
"NAME": "XYZ",
"GENDER": "M"
},
{
"ID": "11",
"NAME": "#XYZ",
"GENDER": "M"
},
{
"ID": "11",
"NAME": "#XYZ",
"GENDER": "M"
}
]
}
]
if your response like above try below code this may help you.
try {
JSONArray jsoArray = new JSONArray(json);
JSONArray JobjArray = jsoArray.getJSONObject(0).getJSONArray("Obj");
for(int i=0; i < JobjArray.length(); i++)
{
JSONObject Jobj = JobjArray.getJSONObject(i);
Iterator<String> iter = Jobj.keys();
while (iter.hasNext()) {
String key = iter.next();
Log.v("key--", key);
try {
Object value = Jobj.get(key);
Log.v("value--", ""+value);
String str_value = value.toString().trim();
if(str_value.startsWith("#"))
{
Log.d(""+str_value,"value started with #");
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources