i get a JSON response from a web service:
{"CoverageSearchByLatLongResult":{"HasTransmissionAreasWithSignal":true,"SwitchOffArea":
{"OpenForVastApplications":false,"SeperateTileSetUrl":"http:\/\/myswitch.merged.stage.orchard.net.au\/geodatafiles\/SwitchOffArea\/442b8844-3c05-4548-9424-
4fdafc1f3c62\/Seperate","HASStatus":"Future","HASStatement":"<p>The Household Assistance Scheme is not yet available in this switchover area. Eligible households will be sent a letter when the scheme opens in the Sydney area.<\/p>","SwitchOffDate":"31 December 2013","Events":{"MaximumProximity":6.864859435168742,"Items":[{"Name":"Test Event","Time":"Time","Url":"","Date":"Date","Address":"19a Boundary Street, Rushcutter...
so my question is, in android java how to ask for the key: CoverageSearchByLatLongResult
in ObjC in iphone , something like this:
NSDictionary *coverageResult = [response objectForKey:#"CoverageSearchByLatLongResult"];
so basically im parsing a dictionary with a key, but that result i need to put it inside other dictionary,
[correct me if wrong, in java dictionaries are called maps?]
how to do this?
thanks a lot!
You should use the classes in the org.json package:
http://developer.android.com/reference/org/json/package-summary.html
With them you can do things like:
try {
String jsonString = "YOUR JSON CONTENT";
JSONObject obj = new JSONObject(jsonString);
JSONObject anotherObj = obj.getJSONObject("CoverageSearchByLatLongResult");
boolean bool = anotherObj.getBoolean("HasTransmissionAreasWithSignal");
JSONArray jsonArray = obj.getJSONArray("arrayKey");
int i = jsonArray.getInt(0);
} catch (JSONException e) {
e.printStackTrace();
}
Java Maps map keys to values. As an example of their use:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("string key", 1);
map.put("another key", 3);
Related
I am trying to parse this json.
However, it is not working ...
I want to parse expected_departure_time of all the buses such as 4 , 15, C1, 4A in departure
this is my code which is not working.
try{
String str = response.getString("departures");
JSONArray jsonArray = response.getJSONArray(str);
JSONObject bus = jsonArray.getJSONObject(0);
String four = bus.getString("expected_departure_time");
textView.append(four);
}catch (JSONException e){
e.printStackTrace();
}
JSON
https://transportapi.com/v3/uk/bus/stop/6090282/live.json?app_id=d7180b02&app_key=47b460aac35e55efa666a99f713cff28&group=route&nextbuses=yes
The error you're making is that you're considering "departures" as a JsonArray, which is not the case in your JSON example, it is a JsonObject (Which in my opinion is a poor way of constructing this Json).
Anyway, you will have to get all the JsonObjects inside the "departure" JsonObject by doing this:
try
{
String jsonString=response.toString();
JSONObject jObject= new JSONObject(jsonString).getJSONObject("departures");
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONArray innerJArray = jObject.getJSONArray(key);
//This is your example, you can add a loop here
innerJArray(0).getString("expected_departure_time");
}
}
catch (JSONException e)
{ e.printStackTrace(); }
If you need to use the transport API for other features, to convert JSON strings to Java objects, you can map automatically by using GSON.
Follow the instructions from Leveraging the gson library and map any response you want from this API.
I have an android app which send jsonobject to server as follow:
JSONObject jsonParam = new JSONObject();
jsonParam.put("snc", serialClient);
jsonParam.put("code", hashString(pwd + serialClient));
printout = new DataOutputStream(urlConn.getOutputStream());
String str = jsonParam.toString();
byte[] data = str.getBytes("UTF-8");
printout.write(data);
printout.flush();
printout.close ();
And the MVC Controller as follow:
<System.Web.Http.AcceptVerbs("Post")> _
Public Function Android_Index(ByVal data As String) As ActionResult
Dim param As Dictionary(Of String, String) = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(data)
For Each p In param
LogEntry(p.Key & vbCrLf & p.Value, 0, "test")
Next
Return RedirectToLocal("/UI/Forbidden")
End Function
But I receive the data as empty-no element object. Please help to find where I am going wrong and how can I fix it?
UPDATE
I have tried to create a MVC class as follow:
Public Class SNC
Public snc As String
Public code As String
End Class
And edit the controller as follow:
Public Function Android_Index(ByVal data As SNC) As ActionResult
LogEntry(data.snc, 0, "test")
LogEntry(data.code, 0, "test")
......
End Function
When the android app tried to send the jsonobject, I can confirm the Android_Index has been hit. So I assume the jsonobject should accepted in the "data" parameter. But both "snc" and "code" are blank string. While I have re-check from the android that both "snc" and "code" which sent as jsonobject is not empty. For now, it seems the problem is in android side. Or the way how mvc should accept is not in correct way?
After hours with nothing, finally I can make it work.
The issue is on java side:
First I have to assign the jsonobject to a key as follow:
JSONObject jsonParam = new JSONObject();
jsonParam.put("snc", serialClient);
jsonParam.put("code", hashString(pwd + serialClient));
String param = "data=" + jsonParam.toString(); //assign jsonParam to identifier
Then set the Content-Type to application/x-www-form-urlencoded.
The post data finally catched correctly by the Controller.
I'm trying to parse the JSON response from google direction api in my android program. This is the request link bellow. I'm skipping the JSON response here because its too long and simply clicking on the link will show it.
http://maps.googleapis.com/maps/api/directions/json?origin=Windsor&destination=Leamington&sensor=false&avoid=highways&mode=walking
My code for parsing the response :
try {
JSONObject responseObject = (JSONObject) new JSONTokener(responseString).nextValue();
this.responseString = responseObject.getString("status") ;
JSONArray routesArray = responseObject.getJSONArray("routes");
JSONObject route = routesArray.getJSONObject(0);
JSONArray legs ;
JSONObject leg ;
JSONArray steps ;
JSONObject dist;
Integer distance ;
if(route.has("legs")) {
legs = route.getJSONArray("legs");
leg = legs.getJSONObject(0) ;
steps = leg.getJSONArray("steps"); // EDIT : I had somehow missed this line before when copying the code from IDE to the website
int nsteps = steps.length() ;
for(int i=0;i<nsteps;i++) {
JSONObject step = steps.getJSONObject(i);
if(step.has("distance")) {
dist = (JSONObject) step.get("distance");// throws exception
//I would like to take the distance value and do something with it
//if(dist.has("value"))
// distance = (Integer) dist.get("value") ;
}
}
}
else
this.responseString = "not found" ;
} catch ( Exception e) {
e.printStackTrace() ;
}
This throws an exception (again skipping because the JSON response is too big. The stack trace shows the entire response string) :
org.json.JSONException: Expected ':' after polyline at character 13837 of {
"routes" : [
{
"bounds" : {
"northeast" : { ....
I have tried using the getJSONObject function instead of get, but I get the same exception.
dist = step.getJSONObject("distance");
Can anyone please help me by pointing out what am I missing here ? I'm not very familiar with parsin JSON on android yet, so it's quite likely that I'm making a silly mistake somewhere. Thanks.
Another similar post on this site, but not quite the same : JSON parsing of Google Maps API in Android App
As you aren't so familiar, i'd suggest parsing JSON using Gson, esp for complex responses. The case would suit better in your case.
I have used Gson for parsing responses from Google Maps API, Places API and more...
You may be better off using Gson to parse, map data and your model classes. Eg.:
Gson gson = new Gson();
ModelClass modelClass= new ModelClass(); //or ArrayList<ModelClass>
modelClass= gson.fromJson(responseContent,ModelClass.class);
//where responseContent is your jsonString
Log.i("Web service response", ""+modelClass.toString());
https://code.google.com/p/google-gson/
For Naming discrepancies(according to the variables in webservice), can use annotations like
#SerializedName. (So no need to use Serializable)
You can use a for-each loop and verify or operate the data from the model classes.
for(Modelclass object: modelClass.getList()) {
}
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?
Also, use a for-each instead of for(;;) where ever possible.
Check these:
Parsing data with gson from google places
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
How to parse google places json
I am working on the same API right now, thought this would also help, for the model classes:
Displaying multiple routes using Directions API in Android
Try this..
steps = leg.getJSONArray("steps");
int nsteps = steps.length() ;
for(int i=0;i<nsteps;i++) {
if(steps.has("distance")) {
JSONObject new_onj = steps.getJSONObject(i);
dist = new_onj.getJSONObject("distance");
if(dist.has("value"))
distance = (Integer) dist.get("value");
}
}
Your for loop never sets a value for step - are you missing a line
step = steps.getJSONObject(i);
at the top of your for loop?
Android 2.3.3
I am integrating Twitter API into my android application. I am using Twitter4j.
I could get the tweets for a particular user, using the below code.
Paging paging = new Paging(1, 40);
List<twitter4j.Status> statuses = twitter.getUserTimeline("xxx", paging);
Log.d(Const.TAG,"Showing Timeline.");
for (twitter4j.Status status : statuses) {
String rawJSON = DataObjectFactory.getRawJSON(status);
}
My requirement is that I need to parse the JSON String (rawJSON), to get some other values like, published date and so on.
I am pretty new to JSON parsing esp., with converting things to JSON. All i know in the above code is that, String rawJSON = DataObjectFactory.getRawJSON(status); converts the Status Object to a String and I can view it by logging it.
How do I convert this String to a JSONObject or a JSONArray? Can someone provide me with a sample code?
I tried the below code, but it gives an exception
try {
JSONObject tweet = new JSONObject(rawJSON);
JSONArray textArray = tweet.getJSONArray("text");
String text = textArray.getString(0);
Log.d(Const.TAG, "Text = "+text);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d(Const.TAG, "Error while converting string to json");
e.printStackTrace();
}
Here's my code to parse a Twitter4j Status. This example get the language of the tweet.
//Status To JSON String
String statusJson = DataObjectFactory.getRawJSON(status);
//JSON String to JSONObject
JSONObject JSON_complete = new JSONObject(statusJson);
//We get another JSONObject
JSONObject JSON_user = JSON_complete.getJSONObject("user");
//We get a field in the second JSONObject
String languageTweet = JSON_user.getString("lang");
I got a way to get values from Status object without the need to convert it into JSON. Of course this is very basic, by I overlooked it.People who have trouble getting values from Status object, can look at this.
You can get all the values by using the object of Status.
For example, if "status" is an object of Status, we can get the text of the tweet, by using, status.getText() and the user value by using status.user() and so on. Just work on the status object a bit and you will find all the values you need.
Purely as an academic exercise I wanted to convert one of my existing GAE applets to return the response back to Android in JSON and parse it accordingly.
The original XML response containing a series of booleans was returned thus:
StringBuilder response = new StringBuilder();
response.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
response.append("<friend-response><added>");
response.append(friendAdded);
response.append("</added><removed>");
response.append(friendRemoved);
response.append("</removed><found>");
response.append(friendFound);
response.append("</found></friend-response>");
I want to replace this with a JSON response that looks something like this:
{ "friendResponse" : [ { "added":true, "removed":false, "found":true } ]}
I think I can generate the array contents as follows (I haven't tested it yet) but I don't know how to create the top-level friendResponse array itself. I can't seem to find any good examples of creating JSON responses in Java using the com.google.appengine.repackaged.org.json library. Can anyone help put me on the right path?
boolean friendAdded, friendRemoved, friendFound;
/* Omitted the code that sets the above for clarity */
HttpServletResponse resp;
resp.setContentType("application/json");
resp.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
try {
//How do I create this as part of a friendResponse array?
json.put("added", friendAdded);
json.put("removed", friendRemoved);
json.put("found", friendFound);
json.write(resp.getWriter());
} catch (JSONException e) {
System.err
.println("Failed to create JSON response: " + e.getMessage());
}
You need to use JSONArray to create the (single-element) array that will store your object:
try {
JSONObject friendResponse = new JSONObject();
friendResponse.put("added", friendAdded);
friendResponse.put("removed", friendRemoved);
friendResponse.put("found", friendFound);
JSONArray friendResponseArray = new JSONArray();
friendResponseArray.put(friendResponse);
JSONObject json = new JSONObject();
json.put("friendResponse", friendResponseArray);
json.write(resp.getWriter());
} catch (JSONException e) {
System.err
.println("Failed to create JSON response: " + e.getMessage());
}
You can use GSON: https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples
With this framework, you can serialize an object to json, and vice versa.