Parsing Json array from webservice to android - java

I am trying to parse this json data from web service to android using volley.
This is the json array to be parsed.
[
{
"id":"1",
"conf_room_name":"Tadoba"
},
{
"id":"2",
"conf_room_name":"Melghat"
},
{
"id":"3",
"conf_room_name":"Ranthambore"
},
{
"id":"4",
"conf_room_name":"Corbett"
},
{
"id":"5",
"conf_room_name":"Pench"
}
]
[
{
"id":"1",
"area":"Mafatlal"
},
{
"id":"2",
"area":"Andheri"
}
]
[
{
"id":"1",
"type":"Is Personal"
},
{
"id":"2",
"type":"Meeting"
}
]
I am using this code to get the value out of my json array object ot different arraylists.
RequestQueue requestQueue2= Volley.newRequestQueue(this);
// RequestQueue requestQueue3= Volley.newRequestQueue(this);
// Create json array request
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST,"http://170.241.241.198/test.php",new Response.Listener<JSONArray>(){
public void onResponse(JSONArray jsonArray){
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject jsonObject=jsonArray.getJSONObject(i);
stringArray_conf.add(jsonObject.getString("conf_room_name"));
stringArray_area.add(jsonObject.getString("area"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Error", "Unable to parse json array");
}
});
requestQueue2.add(jsonArrayRequest);
Only 1st array is being filled properly not the other one. I get outofboundsindex exception whenever i try using values from my 2nd arraylist.
All this happens on a button click only i want this to happen when i load my page.
Any help will be appreciated.

Make JSON as Array as below:
[
[
{
"id": "1",
"conf_room_name": "Tadoba"
},
{
"id": "2",
"conf_room_name": "Melghat"
},
{
"id": "3",
"conf_room_name": "Ranthambore"
},
{
"id": "4",
"conf_room_name": "Corbett"
},
{
"id": "5",
"conf_room_name": "Pench"
}
],
[
{
"id": "1",
"area": "Mafatlal"
},
{
"id": "2",
"area": "Andheri"
}
],
[
{
"id": "1",
"type": "Is Personal"
},
{
"id": "2",
"type": "Meeting"
}
]
]
Or Object (easier to reading and understanding):
{
"rooms": [
{
"id": "1",
"conf_room_name": "Tadoba"
},
{
"id": "2",
"conf_room_name": "Melghat"
},
{
"id": "3",
"conf_room_name": "Ranthambore"
},
{
"id": "4",
"conf_room_name": "Corbett"
},
{
"id": "5",
"conf_room_name": "Pench"
}
],
"areas": [
{
"id": "1",
"area": "Mafatlal"
},
{
"id": "2",
"area": "Andheri"
}
],
"types": [
{
"id": "1",
"type": "Is Personal"
},
{
"id": "2",
"type": "Meeting"
}
]
}
PHP code maybe like below:
<?php
$sqlroom = mysql_query("SELECT * FROM `room_table`");
$room_rows = array();
while($r = mysql_fetch_assoc($sqlroom)) {
$room_rows[] = $r;
}
$sqlarea = mysql_query("SELECT * FROM `area_table`");
$area_rows = array();
while($r = mysql_fetch_assoc($sqlarea)) {
$area_rows[] = $r;
}
$sqltype = mysql_query("SELECT * FROM `type_table`");
$type_rows = array();
while($r = mysql_fetch_assoc($sqltype)) {
$type_rows[] = $r;
}
$result = array();
$result["rooms"] = $room_rows;
$result["areas"] = $area_rows;
$result["types"] = $type_rows;
echo json_encode($result);
?>

You seem to be trying to parse three different types of data: conference rooms, areas (which presumably contain conference rooms?) and some information about either one (although it's not clear which). It therefore doesn't make sense to try and store these in a single array as each element contains a different data structure compared to the other two.
If the type is a description of one of the other two objects then it should be compassed within that object, not treated as a separate one. A room doesn't necessarily have to sit within an area but it might also make sense to have it there.
You say you are "pulling all these values from a mysql server and then using php to encode the json data which gives me the structure of the json array" which implies you do not have direct access to the JSON structure, but you should still have access to the PHP structure. The JSON encoder will use the design of the PHP array / object to structure the JSON so, for this to work you need to create more-or-less matching PHP and Java objects at either end of the serialization process.
For instance:
$obj = (object) array
('id' => '1', 'area' => 'Mafatlal', 'rooms' => array
('id' => '1', 'conf_room_name' => 'Tadoba', 'type' => 'Is Personal'),
...
('id' => '2', 'area' => 'Andheri', 'rooms' => array...
);
and
public class Area {
private int id;
private String area;
private Room[] rooms;
}
public class Room {
private int id;
private String conf_room_name;
private String type;
}
Note that, in contrast to the usual Java camel-case naming convention, object variables will usually have to match the incoming JSON variable name (i.e.: conf_room_name instead of confRoomName).

You need to add values using for loop.
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.toString.contains("conf_room_name"))
stringArray_conf.add(jsonObject.getString("conf_room_name"));
else if(jsonObject.toString.contains("area"))
stringArray_area.add(jsonObject.getString("area"));
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

How to make com.fasterxml.jackson print array vertically? [duplicate]

I have data that looks like this:
{
"status": "success",
"data": {
"irrelevant": {
"serialNumber": "XYZ",
"version": "4.6"
},
"data": {
"lib": {
"files": [
"data1",
"data2",
"data3",
"data4"
],
"another file": [
"file.jar",
"lib.jar"
],
"dirs": []
},
"jvm": {
"maxHeap": 10,
"maxPermSize": "12"
},
"serverId": "134",
"version": "2.3"
}
}
}
Here is the function I'm using to prettify the JSON data:
public static String stringify(Object o, int space) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
I am using the Jackson JSON Processor to format JSON data into a String.
For some reason the JSON format is not in the format that I need. When passing the data to that function, the format I'm getting is this:
{
"status": "success",
"data": {
"irrelevant": {
"serialNumber": "XYZ",
"version": "4.6"
},
"another data": {
"lib": {
"files": [ "data1", "data2", "data3", "data4" ],
"another file": [ "file.jar", "lib.jar" ],
"dirs": []
},
"jvm": {
"maxHeap": 10,
"maxPermSize": "12"
},
"serverId": "134",
"version": "2.3"
}
}
}
As you can see under the "another data" object, the arrays are displayed as one whole line instead of a new line for each item in the array. I'm not sure how to modify my stringify function for it to format the JSON data correctly.
You should check how DefaultPrettyPrinter looks like. Really interesting in this class is the _arrayIndenter property. The default value for this property is FixedSpaceIndenter class. You should change it with Lf2SpacesIndenter class.
Your method should looks like this:
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
I don't have enough reputation to add the comment, but referring to the above answer Lf2SpacesIndenter is removed from the newer Jackson's API (2.7 and up), so instead use:
printer.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
Source of the solution

JSONObject is not getting converted to String properly

I am converting JSONObject to String. I am using below code:
String decresponse=obj.getFileWithUtil("Files/v3user22.txt");
System.out.println("Decrypted string is "+decresponse);
JSONObject js = JSONObject(decresponse);
System.out.println("JSON Object is "+js.toString());
Here, i am getting the value of decresponse from a file since the json is very large. Value of decresponse is:
{
"userid":123456,
"status":"SUCCESS",
"name":{
"firstName":"firstname",
"lastName":"lastname"
},
"dob":"03/02/1993",
"gender":"M",
"kycType":"Manual",
"address":{
"permanentAddress":{
"country":"INDIA",
"street_1":"K-26",
"street_2":"",
"city":"North",
"state":"Delhi",
"postal_code":"110052",
"locality":"abc"
},
"correspondenceAddress":{
"country":"INDIA",
"street_1":"abc",
"street_2":"abc",
"city":"ABC",
"state":"Punjab",
"postal_code":"111000",
"locality":"def"
}
},
"docs":[
{
"nameOnDoc":"name",
"verificationStatus":"FAILED",
"kycNameMatch":"SUCCESS",
"docCode":"aadhar",
"docValue":"1898989",
"submittedAs":"AdditionalDoc"
},
{
"nameOnDoc":"abc",
"verificationStatus":"NOT_ATTEMPTED",
"kycNameMatch":"NOT_ATTEMPTED",
"docCode":"pan",
"docValue":"KSKA1234F",
"submittedAs":"AdditionalDoc",
"expiryDate":"03/02/2018"
},
{
"docCode":"voter",
"docValue":"CIBPS2107P",
"submittedAs":"Poi_Poa"
}
],
"agents":[
{
"bankAgentType":"BF",
"agentBranch":"nodia",
"agentDesignation":"agent manager",
"agentEmpcode":"1010111",
"custId":"119990",
"agentId":"",
"agencyType":"CFA",
"agencyName":"internal"
},
{
"bankAgentType":"BC",
"agentBranch":"nodia",
"agentDesignation":"agent manager",
"agentEmpcode":"",
"custId":"119999",
"agentId":"MORPHO-1782",
"agencyType":"VA",
"agencyName":"morpho"
}
],
"relatives":[
{
"relationShip":"FATHER",
"firstName":"firstname",
"lastName":"lastname"
},
{
"relationShip":"MOTHER",
"firstName":"firstname",
"lastName":"lastname"
}
],
"useKycDetails":"UNDER_REVIEW",
"amlflags":{
"sanction":"N",
"pep":"N"
},
"walletflags":{
"upgraded":"1",
"updated":"1",
"blocked":"0"
},
"suspended":"false",
"aadhar_type1_check":"FAILED",
"aadhar_kyc_name_check":"SUCCESS",
"aadharSubmittedAs":"AdditionalDoc",
"aadharVerified":"false",
"panSubmittedAs":"AdditionalDoc",
"panVerified":"false",
"maritalStatus":"MARRIED",
"profession":"PRIVATE_SECTOR_JOB",
"nationality":"INDIAN",
"kycVerificationDate":"04/01/2017",
"declarationPlace":"Delhi",
"dmsInfos":[
{
"type":"",
"dmsid":""
}
],
"aadharAuthCode":"56bd65db0dbc4b2a848841a44eabb54e",
"agriculturalIncome":"100000",
"nonAgriculturalIncome":"50000",
"seedingStatus":"consent_given"
}
But, on converting the json object to string the value comes as below:
{
"panVerified":"false",
"gender":"M",
"userid":123456,
"panSubmittedAs":"AdditionalDoc",
"aadharAuthCode":"56bd65db0dbc4b2a848841a44eabb54e",
"docs":[
{
"kycNameMatch":"SUCCESS",
"verificationStatus":"FAILED",
"nameOnDoc":"name",
"docCode":"aadhar",
"docValue":"1898989",
"submittedAs":"AdditionalDoc"
},
{
"expiryDate":"03/02/2018",
"kycNameMatch":"NOT_ATTEMPTED",
"verificationStatus":"NOT_ATTEMPTED",
"nameOnDoc":"abc",
"docCode":"pan",
"docValue":"KSKA1234F",
"submittedAs":"AdditionalDoc"
},
{
"docCode":"voter",
"docValue":"CIBPS2107P",
"submittedAs":"Poi_Poa"
}
],
"aadhar_type1_check":"FAILED",
"aadharSubmittedAs":"AdditionalDoc",
"useKycDetails":"UNDER_REVIEW",
"kycVerificationDate":"04/01/2017",
"kycType":"Manual",
"profession":"PRIVATE_SECTOR_JOB",
"address":{
"permanentAddress":{
"country":"INDIA",
"street_1":"K-26",
"city":"North",
"street_2":"",
"locality":"abc",
"state":"Delhi",
"postal_code":"110052"
},
"correspondenceAddress":{
"country":"INDIA",
"street_1":"abc",
"city":"ABC",
"street_2":"abc",
"locality":"def",
"state":"Punjab",
"postal_code":"111000"
}
},
"nonAgriculturalIncome":"50000",
"seedingStatus":"consent_given",
"dmsInfos":[
{
"dmsid":"",
"type":""
}
],
"relatives":[
{
"firstName":"firstname",
"lastName":"lastname",
"relationShip":"FATHER"
},
{
"firstName":"firstname",
"lastName":"lastname",
"relationShip":"MOTHER"
}
],
"suspended":"false",
"agents":[
{
"agentId":"",
"agentEmpcode":"1010111",
"custId":"119990",
"agentBranch":"nodia",
"agentDesignation":"agent manager",
"bankAgentType":"BF",
"agencyType":"CFA",
"agencyName":"internal"
},
{
"agentId":"MORPHO-1782",
"agentEmpcode":"",
"custId":"119999",
"agentBranch":"nodia",
"agentDesignation":"agent manager",
"bankAgentType":"BC",
"agencyType":"VA",
"agencyName":"morpho"
}
],
"amlflags":{
"sanction":"N",
"pep":"N"
},
"aadhar_kyc_name_check":"SUCCESS",
"nationality":"INDIAN",
"dob":"03/02/1993",
"walletflags":{
"upgraded":"1",
"blocked":"0",
"updated":"1"
},
"name":{
"firstName":"firstname",
"lastName":"lastname"
},
"aadharVerified":"false",
"maritalStatus":"MARRIED",
"status":"SUCCESS",
"declarationPlace":"Delhi",
"agriculturalIncome":"100000"
}
Why am I getting different values?
Why am I getting different values
Those values are not that different. They simply have key:value pairs in different order.
JSON structure holds key:value pairs where keys are unique. In most cases order of keys is not important so classes like org.json.JSONObject are storing them in internal HashMap which doesn't preserve insertion order (but allows quick access to values).
When toString() is invoked internally it builds String using that HashMap iterator, so order depends on amount of keys and their hashes, not insertion order.
If you want to preserve order consider using other libraries like gson. Your parsing could look like:
JsonParser jsonParser = new JsonParser();
JsonObject js = jsonParser.parse(decresponse).getAsJsonObject();
and js.toString() would result in
{"userid":123456,"status":"SUCCESS","name":{"firstName":"firstname", ... which seems to be what you ware after.

parsing data from JSON using Volley in Android

I tried parsing JSON data from "https://api.instagram.com/v1/media/popular?client_id="
+ clientId; or any other url, in a tons of different ways! Used couple of JSONParsers, tutorials, readers .. everything, but still can't to get anything from those urls. Now I am using Volley library and still can't get it to work, here is my code and everything you need, if anyone has any ideas , please share them.
public void LoadPictures() {
mRequestQueue = Volley.newRequestQueue(this);
mRequestQueue.add(new JsonObjectRequest(urlInst, null,
new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
parseJSON(response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}));
this is my parseJSON method:
private void parseJSON(JSONObject json) throws JSONException{
// JSONObject value = json.getJSONObject("value");
JSONArray items = json.getJSONArray("data");
for(int i=0;i<items.length();i++) {
JSONObject c=(JSONObject) items.get(i);
JSONObject user = c.getJSONObject("user");
String name= user.getString("username");
JSONObject img=c.getJSONObject("images");
JSONObject thum=img.getJSONObject("thumbnail");
String urlOfPic = thum.getString("url");
PhotoInst photoData=new PhotoInst (i, urlOfPic, name);
photos.add(photoData);
}
this is JSON data I was supposed to get :
"data": [{
"type": "image",
"users_in_photo": [],
"filter": "Gotham",
"tags": [],
"comments": { ... },
"caption": {
"created_time": "1296656006",
"text": "ãã¼ãâ¥ã¢ããªå§ãã¦ä½¿ã£ã¦ã¿ãã(^^)",
"from": {
"username": "cocomiin",
"full_name": "",
"type": "user",
"id": "1127272"
},
"id": "26329105"
},
"likes": {
"count": 35,
"data": [{
"username": "mikeyk",
"full_name": "Kevin S",
"id": "4",
"profile_picture": "..."
}, {...subset of likers...}]
},
"link": "http://instagr.am/p/BV5v_/",
"user": {
"username": "cocomiin",
"full_name": "Cocomiin",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1127272_75sq_1296145633.jpg",
"id": "1127272"
},
"created_time": "1296655883",
"images": {
"low_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/01/34d027f155204a1f98dde38649a752ad_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/01/34d027f155204a1f98dde38649a752ad_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/01/34d027f155204a1f98dde38649a752ad_7.jpg",
"width": 612,
"height": 612
}
},
"id": "22518783",
"location": null
},
when I try putting random Toasts to see where is the problem, I can see the onResponse in my method LoadPictures isn't called at all? Where am I failing ? am I just overseeing something small or something else?
#Mate - As visible from your json, you are getting a JsonArray i.e. "data". Hence, change your Listener to Listener<JSONArray> whihc ensures that it returns a JSONArray object. As a result your onResponse will now become,
#Override
public void onResponse(JSONArray response) {
try {
parseJSON(response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Let me know if this works.
A few things you should verify first:
Are you sure you have the following in your manifest?
<uses-permission android:name="android.permission.INTERNET" />
Instagram requires some sort of API Key / authentication. Are you sure you are providing this?
Is your ErrorListener printing a stack trace? If it is, can you provide it?
That is where I would start.
may this help you response = response.substring(5); makes to remove first 5 characters like data: and continue with JSONArray jsonArray = new JSONArray(response);

Finding deeply nested key/value in JSON

Suppose I have a JSON array like this:
[
{
"id": "429d30a1-9364-4d9a-92e0-a17e00b3afba",
"children": [],
"parentid": "",
"name": "Expo Demo"
},
{
"id": "f80f1034-9110-4349-93d8-a17e00c9c317",
"children":
[
{
"id":"b60f2c1d-368b-42c4-b0b2-a1850073e1fe",
"children":[],
"parentid":"f80f1034-9110-4349-93d8-a17e00c9c317",
"name":"Tank"
}
],
"parentid": "",
"name": "Fishtank"
},
{
"id": "fc8b0697-9406-4bf0-b79c-a185007380b8",
"children": [
{
"id":"5ac52894-4cb6-46c2-a05a-a18500739193",
"children":[
{
"id": "facb264c-0577-4627-94a1-a1850073c270",
"children":[
{
"id":"720472b5-189e-47f1-97a5-a18500a1b7e9",
"children":[],
"parentid":"facb264c-0577-4627-94a1-a1850073c270",
"name":"ubSubSub"
}],
"parentid": "5ac52894-4cb6-46c2-a05a-a18500739193",
"name": "Sub-Sub1"
}],
"parentid":"fc8b0697-9406-4bf0-b79c-a185007380b8", "name":"Sub"
},
{
"id":"4d024610-a39b-49ce-8581-a18500739a75",
"children":[],
"parentid":"fc8b0697-9406-4bf0-b79c-a185007380b8",
"name":"Sub2"
}
],
"parentid": "",
"name": "Herman"
},
{
"id": "a5b140c9-9987-4e6d-a883-a18c00726883",
"children": [
{
"id":"fe103303-fd5e-4cd6-81a0-a18c00733737",
"children":[],
"parentid":"a5b140c9-9987-4e6d-a883-a18c00726883",
"name":"Contains Spaces"
}],
"parentid": "",
"name": "Kiosk"
}
]
No I want to find a certain object based on a id and once I have that, I need its children and all its childrends children
So lets say i want to find the element with an id if 4d024610-a39b-49ce-8581-a18500739a75
That should find the Element Sub2
And now it should produce all the child elements ids witch will be:
facb264c-0577-4627-94a1-a1850073c270
720472b5-189e-47f1-97a5-a18500a1b7e9
Let say I would do
findElementsChildren("4d024610-a39b-49ce-8581-a18500739a75")
So i guess its two parts, first find the "parent" element. Then find its childrends childrends children etc..
Any help would be much appreciated!
You can use recursion to solve the problem of unlimited nesting. With Gson, it would be something like the following code snippet (not tested). Other libraries will provide structures as JsonElement as well.
private JsonElement findElementsChildren(JsonElement element, String id) {
if(element.isJsonObject()) {
JsonObject jsonObject = element.getAsJsonObject();
if(id.equals(jsonObject.get("id").getAsString())) {
return jsonObject.get("children");
} else {
return findElementsChildren(element.get("children").getAsJsonArray(), id);
}
} else if(element.isJsonArray()) {
JsonArray jsonArray = element.getAsJsonArray();
for (JsonElement childElement : jsonArray) {
JsonElement result = findElementsChildren(childElement, id);
if(result != null) {
return result;
}
}
}
return null;
}
Based on Stefan Jansen's answer I made some changes and this is what I have now:
nestedChildren declared globaly, and before the children are searched reset to new ArrayList()
private void findAllChild(JSONArray array) throws JSONException {
for ( int i=0;i<array.length();i++ ) {
JSONObject json = array.getJSONObject(i);
JSONArray json_array = new JSONArray(json.getString("children"));
nestedChildren.add(json.getString("id"));
if ( json_array.length() > 0 ) {
findAllChild(json_array);
}
}
}
This assumes it is all Arrays, witch in my case it is

Using JSON for nested level

I have the following json ,i am facing issue with creating jsonobject for this.Please let me know how to create a jsonobject with nested levels.
{
"menuConf": {
"class": "menu horizontal dropdown",
"caption": "",
"id": "mainMenu",
"container": "div",
"contClass": "navigation main left",
"helper": "span",
"items": [
{
"caption": "a",
"class": "orangesec",
"link": "#",
"id": "subMenu_1",
"helper": "span",
"items": [
{
"caption": "b",
"link": "#b"
},
{
"caption": "b",
"link": "#b"
},
{
"caption": "Blbogs",
"link": "#b"
},
{
"caption": "b",
"link": "#b"
}
]
}
]
}
}
What's wrong with the JSONObject(String) constructor? Just store your JSON text in a string and use it - it should handle nested objects just fine:
String json = "{...}";
try {
JSONObject o = new JSONObject(json);
// Print out the JSON text with a 4-space indentation
System.out.println(o.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}

Categories