Android JSON for statement JAVA - java

The output keeps repeating the name for each property. Only need to see the name once, and then prop_name and address can print out for each occassion under the single name. The JSON looks like:
[{"pmid":"2","name":"CARLYLE MANAGEMENT","result":"1","properties":[{"prop_id":"32","prop_name":"Bonneville Tower","address":"25801 Lakeshore","city":"Euclid","state":"OH","zip":"44132","lat":"41.6223","long":"-81.5034"}]},
{"pmid":"1","name":"COMMERCIAL ONE REALTY","result":"18","properties":[{"prop_id":"3","prop_name":"Autumn Chase Apartments","address":"146 Grand Circuit Blvd.","city":"Delaware","state":"OH","zip":"43015","lat":"40.3105","long":"-83.1138"},
{"prop_id":"6","prop_name":"Barrington Club Apartments","address":"4600 Barrington Club","city":"Columbus","state":"OH","zip":"43220","lat":"40.0536","long":"-83.0448"},{"prop_id":"17","prop_name":"Battleship Building Condominium","address":"444 North Front St.","city":"Columbus","state":"OH","zip":"43215","lat":"39.9712","long":"-83.0042"}]
The code is currently:
String pmid = mJsonObject.getString("pmid");
String name = mJsonObject.getString("name");
String result = mJsonObject.getString("result");
JSONArray mJsonArrayProperty = mJsonObject.getJSONArray("properties");
int innerLength = mJsonArrayProperty.length();
for (int k = 0; k < innerLength; k++) {
// JSONArray mJsonArrayProperty = mJsonObject.getJSONArray("properties");
// for (int i = 0; i < mJsonArrayProperty.length(); i++) {
JSONObject mJsonObjectProperty = mJsonArrayProperty.getJSONObject(k);
String prop_id = mJsonObjectProperty.getString("prop_id");
String prop_name = mJsonObjectProperty.getString("prop_name");
String address = mJsonObjectProperty.getString("address");
String city = mJsonObjectProperty.getString("city");
String state = mJsonObjectProperty.getString("state");
String zip = mJsonObjectProperty.getString("zip");
String lat = mJsonObjectProperty.getString("lat");
String lon = mJsonObjectProperty.getString("long");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_EMAIL, prop_name);
contact.put(TAG_NAME, name);
contact.put(TAG_PHONE, address);
// adding contact to contact list
contactList.add(contact);
}
} }catch (JSONException e) {
e.printStackTrace();
}
The output gives me the prop_name and address but it also says the name over and over each time. The goal is to see the name once and then the multiple properties under it. How can this be accomplished with a for or if statement, or any other way.

I am just writing the algo, How you can do it...
First you have to get the JSONObject in which you have the jsondata.
From that JSONObject you should get JSONArray because the whole jsondata you have is an array.
Now from that JSONArray you should get the string pmid, name etc..
Now again you have to get JSONArray because properties is JSONArray now you can iterate it.
And for doing this you should have use two for loop or any iteration method you want to use.

Try Out this...
JSONArray one=new JSONArray(json);
for (int i = 0; i < one.length(); i++)
{
JSONObject jsonObject=one.getJSONObject(i);
String pmid=jsonObject.getString("pmid");
String name=jsonObject.getString("name");
String result=jsonObject.getString("result");
JSONArray properties=jsonObject.getJSONArray("properties");
for (int j = 0; j < properties.length(); j++)
{
JSONObject js=properties.getJSONObject(j);
String prop_id=js.getString("prop_id");
String prop_name=js.getString("prop_name");
String address=js.getString("address");
String city=js.getString("city");
String state=js.getString("state");
String zip=js.getString("zip");
String lat=js.getString("lat");
String Long=js.getString("long");
}
}

Related

Parsing a bit more complex JSON in Java

I have a JSON I need to parse:
I work in Java and I know how to parse basic stuff, but I don't know how to handle JSON like this. Every monumentid may have multiple objects in oteviracidoba.
Without the "oteviraci doba", I was parsing my JSON like this:
Iterator keys = response.keys();
while (keys.hasNext()) {
int cislo = 0;
Object key = keys.next();
JSONObject value = response.getJSONObject((String) key);
String monumentnumber = value.getString("monumentid");
String monumentname = value.getString("name");
String monumentregion = value.getString("region");
String monumentregion2 = value.getString("okres");
String monumenttown = value.getString("obec");
String web = value.getString("web");
String monumentdescription = value.getString("content").replaceAll(" ", " ").replaceAll("Dostupnost", " Dostupnost").replaceAll("postižené:", "postižené: ");
CharSequence descriptionfixed = removeHtmlFrom(monumentdescription);
String description = descriptionfixed.toString();
JSONArray arr = value.getJSONArray("oteviracidoba");
for (int i = 0; i < arr.length(); i++)
{
Object shop = arr.getJSONObject(0);
}
mList.add(new Item(monumentnumber, monumentname, monumentregion, monumentregion2, monumenttown, description, web));
}
Any idea how to do the same thing with this new JSON array so I can add objects in them as an argument for my Item?
Thanks for help!
JSONArray arr = value.getJSONArray("oteviracidoba");
Object[] shops = new Object[arr.length];
for (int i = 0; i < arr.length(); i++) {
shops[i] = arr.getJSONObject(i);
}
//if item has array of objects in its constructor then pass it there.
mList.add(new Item(monumentnumber, monumentname, monumentregion, monumentregion2, monumenttown, description, web, shops));

Read specific items from JSON http request

I get JSON from a rest server (jax rs) through a http request.
[{"carId":"t0","movements":[{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":8,"lane":{"laneId":"--104_0"},"position":73.76,"speed":14.49,"timeStep":8.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":16,"lane":{"laneId":"--104_0"},"position":89.35,"speed":15.59,"timeStep":9.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":27,"lane":{"laneId":"--104_0"},"position":106.39,"speed":17.03,"timeStep":10.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":35,"lane":{"laneId":"--104_0"},"position":125.24,"speed":18.85,"timeStep":11.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":
Just to give you an idea how the JSON looks like.
Now I want to convert every item of this JSON file to an Java object.
So I want to see inside the "fromNode" to get the attributes to make an object.
I can see all the movement and edges, thats no problem (i do that like this):
String jsonStringMike = callURL("http://----------/");
try {
JSONArray jsonArrayMike = new JSONArray(jsonStringMike);
int countMike = jsonArrayMike.length(); // get totalCount of all jsonObjects
for (int i = 0; i < countMike; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArrayMike.getJSONObject(i); // get jsonObject # i position
JSONArray movement = jsonObject.getJSONArray("movements");
String edge = movement.getJSONObject(i).getString("edge");
System.out.println(edge);
So this provides me with all the "edge's" From the JSON file shown before. But if I want to see the "fromNode" I get the following error:
org.json.JSONException: JSONObject["edge"] is not a JSONArray.
This is the code that is not working and will provide the given error.
public static void main(String[] args) throws IOException, JSONException {
String jsonStringMike = callURL("http://6--------------");
try {
JSONArray jsonArrayMike = new JSONArray(jsonStringMike);
int countMike = jsonArrayMike.length(); // get totalCount of all jsonObjects
for (int i = 0; i < countMike; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArrayMike.getJSONObject(i); // get jsonObject # i position
JSONArray movement = jsonObject.getJSONArray("movements");
int o = movement.length();
String test = movement.toString();
JSONArray jsonArray2 = new JSONArray(test);
for (int p = 0; p < o; o++) {
JSONObject moveObject = jsonArray2.getJSONObject(p);
JSONArray edge = moveObject.getJSONArray("edge");
String fromNode = edge.getJSONObject(p).getString("fromNode");
System.out.println(fromNode);
}
Does anybody knows how I can look "deeper" into the given JSON file?
I think you are almost there, the issue in your code that in the loop moveObject is your edge json object, so movemen.length() is the the count of all edge json objects in the array. I have not tested this, but I think it should work. Also, your for loop has typo, o++ should be p++,
JSONArray jsonArrayMike = new JSONArray(jsonStringMike);
int countMike = jsonArrayMike.length(); // get totalCount of all jsonObjects
for (int i = 0; i < countMike; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArrayMike.getJSONObject(i); // get jsonObject # i position
JSONArray movement = jsonObject.getJSONArray("movements");
int o = movement.length();
for (int p = 0; p < o; p++)
{
JSONObject movementObject = movement.getJSONObject(p);
JSONObject edgeObject = movementObject.getJSONObject("edge");
JSONObject fromNode = edgeObject.getJSONObject("fromNode");
String latitude = fromNode.getString("latitude");
String longitude = fromNode.getString("longitude");
String nodeId = fromNode.getString("nodeId");
System.out.println(fromNode);
}
}

new to json parsing - how to get an array within an array

from the following link , I need to get the value stored in "media".
Here is my code:
Content = Content.replace("jsonFlickrFeed(", "");
Content = Content.replace("})", "}");
jsonResponse = new JSONObject(Content);
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
But I can not access past "items"
You will have to loop through the JSON like this:
...
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");
for (int i=0; i<jsonMainNode.length(); i++) {
String media = jsonMainNode.getJSONObject(i).getString("media");
}
This will loop through the images and return the value(s) in media.
In your case it should be something like this:
..
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");
for (int i=0; i<jsonMainNode.length(); i++) {
JSONObject finalNode = jsonMainNode.getJSONObject(i);
JSONArray finalArray = finalNode.optJSONArray("media");
for (int j=0; j<finalArray.length(); j++) {
String m = finalArray.getJSONObject(j).getString("m");
}
}
...because there is another node inside the media node, called m.
Here is an example getting the tags string for each item in the JSONArray that you have:
for (int i = 0; i < jsonMainNode.length(); i++){
JSONObject jsonObject = jsonMainNode.getJSONObject(i);
String tags = jsonObject.getString("tags");
}
This will iterate through all JSONObjects that are in the array, and extract the tags field from each object.
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject item = (JSONObject) jsonMainNode.get(i);
JSONObject media = item.getJSONObject("media");
String valueMedia = media.getString("m");
Log.d("TAG", valueMedia);
}

Get JSON Array into strings.

I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks
try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}
Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}
So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.
You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Extract specific value from a filter-list (auto-complete field)

in my application I'm trying to extract the values from a filter list (auto-complete field).
In that field I have [ID, Name] ex [j342234, A,S]. I was able to retrieve the whole criteria by
doing this
Object Filterlistresult = fliterList.getCriteria();
but now I want to get extract ID part only from that field. Any Ideas?
Thank you in advance.
// here I get the values from a web server and insert them to the work Vector
public void parseJSONResponceInWB(String jsonInStrFormat) {
try {
JSONObject json = new JSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("transport");
for (int i = 1; i < jArray.length(); i++) {
JSONObject j = jArray.getJSONObject(i);
ID = j.getString("ID");
Name = j.getString("Name");
WBenchVector.addElement(ID + " " + Name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// adding the values to the filter list
private void RequestAutoComplete() {
String[] returnValues = new String[WBenchVector.size()];
System.out.print(returnValues);
for (int i = 0; i < WBenchVector.size(); i++) {
returnValues[i] = (String) WBenchVector.elementAt(i);
}
autoCompleteField(returnValues);
}
// creating the filter list field
private void autoCompleteField(String[] returnValues) {
filterLst = new BasicFilteredList();
filterLst.addDataSet(ID, returnValues, "",
BasicFilteredList.COMPARISON_IGNORE_CASE);
autoFld.setFilteredList(filterLst);
}
Finally i'm getting what the user select using this
AutoFieldCriteria = filterLst.getCriteria();
Thank you Nate. I actually fixed the problem.
I converted the filterField Object to String and then I looked for the index of the first space, and substring the first word
Object AutoFieldCriteria = filterLst.getCriteria();
String AutoFieldString = AutoFieldCriteria.toString();
int spacePos = AutoFieldString.indexOf(" ");
String AutoFieldFirstWord = AutoFieldString.substring(0,spacePos);
Thanks again.

Categories

Resources