Android JSON object Parsing, unable to get status - android

{"Sam":{"status":"available","classkey":"dotnet"}}
How to parse this type of json?
try {
JSONObject jObj = new JSONObject(json);
if(jObj != null){
domtdl = jObj.getString(dom);
try {
JSONObject c = new JSONObject(domtdl);
if(c != null){
status = c.getString(TAG_STATUS);
System.out.println(status);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Is it correct?
I do not know how to get data from second JSON object.
Please help me.

For this specific json string {"Sam":{"status":"available","classkey":"dotnet"}}
you need to do
try {
JSONObject jObj = (new JSONObject(json)).getJSONObject("Sam");
String status = jObj.getString("status");
String classkey = jObj.getString("classkey");
} catch (JSONException e) {
e.printStackTrace();
}

try
{
JSONObject jb = new JSONObject(myjsonstring);
JSONObject job = jb.getJSONOBject("Sam");
String status = job.getString("status");
Log.i("Status is",status);
String classkey = job.getString("classkey");
Log.i("Class Key is",classkey);
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{ represents a json object node
{ // json object node
"Sam": { // json object SAM
"status": "available", json string
"classkey": "dotnet" json string
}
}
JSON Tutorial #
http://www.w3schools.com/json/
Your json can also look like below sometimes.
[ represents json array node
{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
To parse the above
StringBuilder sb = new StringBuilder();
try {
JSONObject jb = new JSONObject(myjsonstring);
JSONArray jarr = jb.getJSONArray("employees");
for(int i=0;i<jarr.length();i++)
{
JSONObject job = jarr.getJSONObject(i);
String firstname = job.getString("firstName");
String lastname = job.getString("lastName");
sb.append(firstname);
Log.i("firstname",firstname);
sb.append("\n");
Log.i("lastname",lastname);
}
Toast.makeText(getApplicationContext(), sb, 10000).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

Android : How to access a JSONObject

I'm new to Android and I have tried so many options to access the JSONObject which returns from an API call but I couldn't succeed as any of the solutions i looked for didn't work for me.
What i want is to access the JSONObject and keep the Id & Name in a Array. And then populate the Names in a AutoCompleteTextView. How do i properly access the JSONObject. Please help me with this. I'm stuck on this for more than a day.
Following is my Code handling the JSONObject.
#Override
public void processFinish(JSONObject output) {
Toast.makeText(MainActivity.this,"ProcessFinish",Toast.LENGTH_SHORT).show();
allStations = output;
if(output != null){
Toast.makeText(MainActivity.this,output.toString(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this," Connection Failed!",Toast.LENGTH_SHORT).show();
}
}
Following is a sample output of my JSONObject
{
"SUCCESS": true,
"MESSAGE": "Found 398 Results!",
"NOFRESULTS": 3,
"RESULTS": {
"stationList": [
{
"stationCode": "ABN",
"stationID": 3,
"stationName": "ABLA"
},
{
"stationCode": "ADLA",
"stationID": 410,
"stationName": "ADLA"
},
{
"stationCode": "ANM",
"stationID": 11,
"stationName": "AHAMA"
}]
},
"STATUSCODE": "2000"
}
try this
try {
JSONObject obj= output.getJSONObject("RESULTS");
JSONArray dataArray= obj.getJSONArray(“stationList“);
for(int i=0;i<dataArray.length();i++)
{
JSONObject object1=dataArray.getJSONObject(i);
Strind id = object1.getString("stationID");
}
} catch (JSONException e) {
e.printStackTrace();
}
In This code output is your JSONObject result
try this
try {
JSONObject jsonObject = new JSONObject("response");
boolean status= jsonObject.getBoolean("SUCCESS");
String MESSAGE= jsonObject.getString("MESSAGE");
String NOFRESULTS= jsonObject.getString("NOFRESULTS");
String STATUSCODE= jsonObject.getString("STATUSCODE");
JSONObject obj=jsonObject.getJSONObject("RESULTS");
JSONArray jsonarray = obj.optJSONArray("stationList");
for (int i = 0; i < jsonarray.length(); i++){
JSONObject json_data = jsonarray.getJSONObject(i);
Log.e("stationCode",json_data.getString("stationCode"));
Log.e("stationID",json_data.getString("stationID"));
Log.e("stationName",json_data.getString("stationName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried using a JSON Array? For example you could use this method for storage:
JSONObject wgroup = new JSONObject(); //FINAL json object
try { //put initial data
wgroup.put("id", "2");
wgroup.put("user", "someone");
wgroup.put("stime", "2017-02-06 16:30:13");
wgroup.put("etime", "2017-02-06 19:30:13");
wgroup.put("real_dur", 3600);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray1 = new JSONArray(); //Create an array to store ALL Variables
for (int y=0; y< your_array.length ; y++ ){ //loop through your information array
JSONObject output = new JSONObject(); //CREATE a json object to put 1 workout
try {
wgroup.put("id", "2");
wgroup.put("name", "sam");
wgroup.put("age", "3");
wgroup.put("gender", "male");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray2 = new JSONArray(); //CREATE a json array to put 1 array
jsonArray1.put(output); //insert this OBJECT into the ARRAY
}
wgroup.put(jsonArray1);//insert the workouts ARRAY into the original object

How do i write nested JSON into HashMap<String,String>?

JSON:
{
"deviceId": "AAAAAAA1",
"cardInfo": {
"pan": "123456789012345",
"psn": "00",
"cvv": "123",
"panExpiryDate": "2017-12-12"
},
"productType": "CREDIT",
"requestor": 1234,
"aid": "A000000001234567",
"aidVersion": 1,
"panSource": null,
"deviceLanguage": "en"
}
Android Code:
protected String doInBackground(Void... params) {
Bundle bundle=getIntent().getExtras();
final String newdata=bundle.getString("newdata");
try {
js=new JSONObject(newdata);
di=js.getString("deviceId");
} catch (JSONException e) {
e.printStackTrace();
}
postDataParams = new HashMap<String, String>();
postDataParams.put("deviceId",deviceID);
postDataParams.put("cardInfo.pan",card);
postDataParams.put("cardInfo.psn",Psn);
postDataParams.put("cardInfo.cvv",cvv);
postDataParams.put("cardInfo.panExpiryDate",panExpiryDate);
postDataParams.put("productType",productType);
postDataParams.put("requestor",requestor);
postDataParams.put("aid",aid);
postDataParams.put("aidVersion",aidVersion);
postDataParams.put("panSource",panSource);
postDataParams.put("deviceLanguage",deviceLanguage);
response = service.postServerData(path,postDataParams);
try {
json = new JSONObject(response);
System.out.println("success " + json.get("success"));
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
On writing this code am not getting any response from the url. Can you please help where i did the mistake.
Change this
postDataParams.put("cardInfo.pan",card);
postDataParams.put("cardInfo.psn",Psn);
postDataParams.put("cardInfo.cvv",cvv);
postDataParams.put("cardInfo.panExpiryDate",panExpiryDate);
to this
JSONObject cardInfoJson = new JSONObject();
cardInfoJson.put("pan", card);
cardInfoJson.put("psn", psn);
cardInfoJson.put("cvv", cvv);
cardInfoJson.put("panExpiryDate", panExpiryDate);
postDataParams.put("cardInfo", cardInfoJson);

append data to existing JSON file

I'm using this code:
JSONObject jO = new JSONObject();
try {
jO.put("item1", true);
jO.put("item2", value2);
jO.put("item3", value3);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String json = null;
try {
json = jO.toString(4);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
File jsonFile = new File(nContext.getDir("json", 0), "dashboard.json");
//simple utility method to write the json file
Utils.writeToFile(jsonFile, json);
to have this result:
{
"item3": "12345",
"item2": "abcde",
"item1": true
}
What I want to achieve, on the next run of the same piece of code, is to end with something like:
{
"pass1": {
"item3": "12345",
"item2": "abcde",
"item1": true
},
"pass2": {
"item3": "67890",
"item2": "zxcvb",
"item1": true
}
}
Or maybe is it better to have this?
{
"pass1": [
{
"item3": "12345",
"item2": "abcde",
"item1": true
}
],
"pass2": [
{
"item3": "67890",
"item2": "zxcvb",
"item1": true
}
]
}
I know this implies a change in the code to include a "nested" object/array.
Which one is better, considering that I'll have to parse the JSON to build a ListView?
Any ideas?
I found the solution, thanks to the comments by other users and to a "retired" answer, not present here anymore. Maybe it was my fault not being clear.
public void addEntryToJsonFile(Context ctx, String id, String name, String size) {
// parse existing/init new JSON
File jsonFile = new File(ctx.getDir("my_data_dir", 0), "my_json_file.json");
String previousJson = null;
if (jsonFile.exists()) {
try {
previousJson = Utils.readFromFile(jsonFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
previousJson = "{}";
}
// create new "complex" object
JSONObject mO = null;
JSONObject jO = new JSONObject();
try {
mO = new JSONObject(previousJson);
jO.put("completed", true);
jO.put("name", name);
jO.put("size", size);
mO.put(id, jO); //thanks "retired" answer
} catch (JSONException e) {
e.printStackTrace();
}
// generate string from the object
String jsonString = null;
try {
jsonString = mO.toString(4);
} catch (JSONException e) {
e.printStackTrace();
}
// write back JSON file
Utils.writeToFile(jsonFile, jsonString);
}
Edited after dentex comment
Read your file
Parse the root Json object
If the root object not is already a complex object
Create a new root object
put your root object in it
put your second object in the root object
Write bnack your file
in pseudo code:
oldJson = ParseJsonFromFile()
newJson = {"item1": true, "item2": "abcde" ...}
JSONObject root;
if (oldJson.hasKey("pass1") {
root = oldJson
} else {
root = new JSONObject()
root.add("pass1", oldJson)
}
root.add("pass" + root.getSize() + 2, newJson)
WriteJsonToFile(root)

Accessing json contents in android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending and Parsing JSON in Android
I have a JSON result in the following format which JSON Lint shows this as a Valid Response.
My question is: how do I accesss the content of "reportId0" value "164", "reportId1" value 157,reportId2 value 165, etc are all dynamic values?
My sample code for accessing value of properties.How to get Value reportid And add allvalue in Arraylist?
"properties": {
"link": "",
"approvalsReportCount": 3,
"reportName0": "srcapprovals",
"reportId0": 164,
"reportName1": "Approvals",
"reportId1": 157,
"requests_report_id": "163",
"requests_report_name": "EG approvals",
"reportName2": "fulfillment",
"reportId2": 165
}
This is the best way i found it to get ReportId value.
Below is My code
JSONObject jObj = new JSONObject(result);
JSONObject jsonResultArray = jObj.getJSONObject("results");
JSONObject pro_object = jsonResultArray.getJSONObject("properties");
Iterator keys = pro_object.keys();
while(keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
String value = pro_object.getString(currentDynamicKey);
String upToEightCharacters = currentDynamicKey.substring(0, Math.min(currentDynamicKey.length(), 8));
if(upToEightCharacters.startsWith("reportId"))
{
Log.v("key"," new report ID key " + currentDynamicKey);
Log.v("key"," new report ID key " + pro_object.getString(currentDynamicKey) );
}
}
you can use this
public ArrayList<String> getReportIds() {
boolean isContinue = true;
JSONObject json;
String tag = "reportId";
int i = 0;
ArrayList<String> repIdList = new ArrayList<String>();
JSONObject prop = null;
try {
json = new JSONObject("<your json string>");
prop = json.getJSONObject("properties");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (isContinue) {
String repId = "";
try {
repId = prop.getString(tag + i);
repIdList.add(repId);
i++;
} catch (JSONException e) {
isContinue = false;
e.printStackTrace();
}
}
return repIdList;
}
You can Try This!!
try {
JSONObject jObj = new JSONObject(result);
JSONObject jsonResultArray = jObj.getJSONObject("results");
Log.v("log_tag","json result Array : "+ jsonResultArray);
JSONObject pro_object = jsonResultArray.getJSONObject("properties");
Iterator keys = pro_object.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
String value = pro_object.getString(currentDynamicKey);
approvaldto_Key = new All_Approval_Key_dto();
String upToEightCharacters = currentDynamicKey.substring(0, Math.min(currentDynamicKey.length(), 8));
if(upToEightCharacters.startsWith("reportId"))
{
approvaldto_Key.requestId = pro_object.getString(currentDynamicKey);
fetchrecursUserData.add(approvaldto_Key);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return fetchrecursUserData;
}
You can try below code
String serial= jsonObject.getJSONObject("response").getString("serialNumber");
or
JSONObject json;
try {
json = new JSONObject(buffer.toString());
String accessToken = json.getString("access_token");
return accessToken;
} catch (JSONException e) {
Log.e("Podcast", "There was an error", e);
}

How to use Json Parsing?

Following is My Json File:-
"Restaurants":{
"8":{
"Res_name":"Purple Cafe and Wine Bar",
"foodtype":"American, Wine",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"9":{
"Res_name":"Quinn's",
"foodtype":"American, Pubs",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"19":{
"Res_name":"Dahlia Lounge",
"foodtype":"American",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
},
I am Using below code for json parsing:-
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurant = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
System.out.println("mRestaurant is:- " + mRestaurant);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The mRestaurant Value is below:-
{"487":{"state":"WA","Res_name":"SAM Taste","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"332":{"state":"WA","Res_name":"Luna Park Cafe","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"35":{"state":"WA","Res_name":"Restaurant Zoe","longitude":"0","latitude":"0","foodtype":"American, Bar","city":"Seattle"},"
but what is the next step for getting Res_Name, foodtype from above response.
Any Help would be appreciated.
The below code is next step for json parsing.
public void getdata() {
String res = mWebRequest.performGet(Constants.url+ "restaurants.php? action=searchRestaurant&lat=0&lon=0&foodtype="+ mEdttxtSearch.getText().toString() + "&state="+ mEdttxtSearch.getText().toString() + "&city="+ mEdttxtSearch.getText().toString()+ "&devType=Android");
System.out.println("res is:- " + res);
if (res != null) {
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurants = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
if (jsonObj.has("Restaurants")) {
Iterator<Object> keys = mRestaurants.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
JSONObject obj = new JSONObject();
obj = mRestaurants.getJSONObject(key);
mRes_Name.add(obj.getString("Res_name"));
mLatitude.add(obj.getString("latitude"));
mLongitude.add(obj.getString("longitude"));
mState.add(obj.getString("state"));
mCity.add(obj.getString("city"));
mFood_Type.add(obj.getString("foodtype"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Use the get() method:
String mRestaurant = jsonObj.get("487").get("Res_name");
use gson for the same, as it supports direct conversion from json to java and java to json, please see following link:
Converting JSON to Java

Categories

Resources