Creating a JSON response from Google Application Engine - android

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.

Related

How to parse more then one JSON from TCP/IP server?

How to parse more then one JSON which each ending with null character(through socket TCP/IP).
{"ObjectID":"UHJvY1dpcmVsZXNzTXNn","DeviceCode":"RUNEOjI=","ActiveInputNames":"Q2hlY2sgaW4gRmFpbA==","DeviceInputNo":"999999","Activation":false,"Reset":true,"LocationID":"","LocationGroupText":"","ProtocolText":"","CallBackNo":"OTE5MTgyNTcyMjQ5"}��{"ObjectID":"VFBpbmdPYmplY3Q="}��
As you can see the above response which has 2 JSON's each ending with null character...I can easily parse the single JSON but unable to parse more then one JSON..
It would be great if any one suggest any solutions!!
You can split the json string using the �� and loop through the array:
String s = "{\"ObjectID\":\"UHJvY1dpcmVsZXNzTXNn\",\"DeviceCode\":\"RUNEOjI=\",\"ActiveInputNames\":\"Q2hlY2sgaW4gRmFpbA==\",\"DeviceInputNo\":\"999999\",\"Activation\":false,\"Reset\":true,\"LocationID\":\"\",\"LocationGroupText\":\"\",\"ProtocolText\":\"\",\"CallBackNo\":\"OTE5MTgyNTcyMjQ5\"}��{\"ObjectID\":\"VFBpbmdPYmplY3Q=\"}��";
String[] array = s.split("��");
for (String string: array){
try {
JSONObject json = new JSONObject(string);
//do what ever you want with this
} catch (JSONException e) {
Log.e("Error",Log.getStackTraceString(e));
}
}

How should I parse JSON?

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.

making json structure by code in android

I have the following json structure which i need to send it to server using post request. Please help in making the same structure by code in android.
The json structure is as follows :
{
"
}
}
Since i am newbie to android so please help.
Use the JSONObject class in android, here is an example:
JSONObject object = new JSONObject();
JSONObject cardAcceptorkey = new JSONObject();
try {
//CREATE cardAcceptorkey object
cardAcceptorkey.put("id","CA-IDCode");
cardAcceptorkey.put("name","USA");
...
//CREATE object
object.put("AuditNumber", "451035adss");
object.put("cardAcceptorkey", cardAcceptorkey);
...
} catch (JSONException e) {
e.printStackTrace();
}
More info: http://www.vogella.com/tutorials/AndroidJSON/article.html

json String in android

I have a problem while creating jsonStringer in android. My problem is I have to post values to server using post method.So for that I have to send an array. { "name":"asdf","age":"42","HaveFiles":["abcfile","bedFile","cefFile"]} .
So how can I create a json array for haveFiles? And I don't know the no of files it may varies. So I am creating a string builder and appending the values to that.
when I print the jsonString the stringbuilder show that instead of " it shows \". But when I print the string builder it looks ["abcFile"] like this. but in jsonStringer it prints ["\""abcFile\""]. How I can resolve this issue?
Use this to create json object and pass the json object
try {
JSONObject jObj = new JSONObject(YourString);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
If you want jsonArray then
jobj.getJSONArray(TAG_NAME);
It is really simple, you can use GSON library to do it.
The usage is something like:
Gson gson = new Gson();
String jsonStr = gson.toJson(yourObj);
YourObjType yourObj2 = gson.fromJson(jsonStr, YourObjType.class);
Regarding to your situation, you can do:
Gson gson = new Gson();
String[] ss = new String[] {"abcFile", "defFile", "ghiFile"};
String jsonStr = gson.toJson(ss);
And the result of jsonStr is:
["abcFile, defFile, ghiFile"]

Sending and Parsing JSON Objects in Android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I would like to send messages in the form of JSON objects to a server and parse the JSON response from the server.
Example of JSON object
{
"post": {
"username": "John Doe",
"message": "test message",
"image": "image url",
"time": "current time"
}
}
I am trying to parse the JSON manually by going attribute by attribute. Is there any library/utility I can use to make this process easier?
I am surprised these have not been mentioned: but instead of using bare-bones rather manual process with json.org's little package, GSon and Jackson are much more convenient to use. So:
GSON
Jackson
So you can actually bind to your own POJOs, not some half-assed tree nodes or Lists and Maps.
(and at least Jackson allows binding to such things too (perhaps GSON as well, not sure), JsonNode, Map, List, if you really want these instead of 'real' objects)
EDIT 19-MAR-2014:
Another new contender is Jackson jr library: it uses same fast Streaming parser/generator as Jackson (jackson-core), but data-binding part is tiny (50kB). Functionality is more limited (no annotations, just regular Java Beans), but performance-wise should be fast, and initialization (first-call) overhead very low as well.
So it just might be good choice, especially for smaller apps.
You can use org.json.JSONObject and org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK
GSON is easiest to use and the way to go if the data have a definite structure.
Download gson.
Add it to the referenced libraries.
package com.tut.JSON;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class SimpleJson extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String jString = "{\"username\": \"tom\", \"message\": \"roger that\"} ";
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
Post pst;
try {
pst = gson.fromJson(jString, Post.class);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Code for Post class
package com.tut.JSON;
public class Post {
String message;
String time;
String username;
Bitmap icon;
}
This is the JsonParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Note: DefaultHttpClient is no longer supported by sdk 23, so it is advisable to use target sdk 21 with this code.
There's not really anything to JSON. Curly brackets are for "objects" (associative arrays) and square brackets are for arrays without keys (numerically indexed). As far as working with it in Android, there are ready made classes for that included in the sdk (no download required).
Check out these classes:
http://developer.android.com/reference/org/json/package-summary.html
Other answers have noted Jackson and GSON - the popular add-on JSON libraries for Android, and json.org, the bare-bones JSON package that is included in Android.
But I think it is also worth noting that Android now has its own full featured JSON API.
This was added in Honeycomb: API level 11.
This comprises
- android.util.JsonReader: docs, and source
- android.util.JsonWriter: docs, and source
I will also add one additional consideration that pushes me back towards Jackson and GSON: I have found it useful to use 3rd party libraries rather then android.* packages because then the code I write can be shared between client and server. This is particularly relevant for something like JSON, where you might want to serialize data to JSON on one end for sending to the other end. For use cases like that, if you use Java on both ends it helps to avoid introducing android.* dependencies.
Or I guess one could grab the relevant android.* source code and add it to your server project, but I haven't tried that...
You can download a library from http://json.org (Json-lib or org.json) and use it to parse/generate the JSON
you just need to import this
import org.json.JSONObject;
constructing the String that you want to send
JSONObject param=new JSONObject();
JSONObject post=new JSONObject();
im using two object because you can have an jsonObject within another
post.put("username(here i write the key)","someusername"(here i put the value);
post.put("message","this is a sweet message");
post.put("image","http://localhost/someimage.jpg");
post.put("time": "present time");
then i put the post json inside another like this
param.put("post",post);
this is the method that i use to make a request
makeRequest(param.toString());
public JSONObject makeRequest(String param)
{
try
{
setting the connection
urlConnection = new URL("your url");
connection = (HttpURLConnection) urlConnection.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
connection.setReadTimeout(60000);
connection.setConnectTimeout(60000);
connection.connect();
setting the outputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
i use this to see in the logcat what i am sending
Log.d("OUTPUT STREAM " ,param);
dataOutputStream.writeBytes(param);
dataOutputStream.flush();
dataOutputStream.close();
InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
here the string is constructed
while ((line = reader.readLine()) != null)
{
result.append(line);
}
i use this log to see what its comming in the response
Log.d("INPUTSTREAM: ",result.toString());
instancing a json with the String that contains the server response
jResponse=new JSONObject(result.toString());
}
catch (IOException e) {
e.printStackTrace();
return jResponse=null;
} catch (JSONException e)
{
e.printStackTrace();
return jResponse=null;
}
connection.disconnect();
return jResponse;
}
if your are looking for fast json parsing in android than i suggest you a tool which is freely available.
JSON Class Creator tool
It's free to use and it's create your all json parsing class within a one-two seconds.. :D
Although there are already excellent answers are provided by users such as encouraging use of GSON etc. I would like to suggest use of org.json. It includes most of GSON functionalities. It also allows you to pass json string as an argument to it's JSONObject and it will take care of rest e.g:
JSONObject json = new JSONObject("some random json string");
This functionality make it my personal favorite.
There are different open source libraries, which you can use for parsing json.
org.json :- If you want to read or write json then you can use this library.
First create JsonObject :-
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values :-
String id = jsonObj.getString("id");
You can see complete example here
Jackson databind :- If you want to bind and parse your json to particular POJO class, then you can use jackson-databind library, this will bind your json to POJO class :-
ObjectMapper mapper = new ObjectMapper();
post= mapper.readValue(json, Post.class);
You can see complete example here

Categories

Resources