开发者

How to send create a JSON string and send it from server to android?

In my application a user will preform a HTTPrequest to retrieve data from the server.

At the moment on the server side, i preform a database select statement and then use the ResultSetDynaBean to retrieve each row and convert to an object and store in an ArrayList. this all works fine.

 ArrayList<ParkingSpot> spotsList

I then convert eachobject to a JSON string using google GSON library

ArrayList<String> jsonStrings = new ArrayList<String>();
    Gson gson = new Gson();
    for (ParkingSpot ps : spotsList) {
        String json = gson.toJson(ps);
        jsonStrings.add(json);
    }

Each json string looks like this

{"add开发者_如何学Cress":"York Road","zone":"Green","startTime":7.0,"endTime":24.0,"timeAdded":"Jun 16, 2011 11:53:27 AM","psId":898}

there can be up to 1000 of the above strings that i need to send

As you can see i add each to a String ArrayList. i do not think this is correct.

How should i go about sending the information to an android phone.

From the GSON library i can call the below on the android phone

 Spot spot = gson.fromJson(jsonString, Spot.class);
          System.out.println(spot);

But i do not know how retrieve the jsonString from the response of my Servlet(i also do not know how to set it on the servlet side either)


I see that you use gson. It is really easy with it:

Serverside:

ArrayList<ParkingSpot> spotsList = ...
String json = gson.toJson(spotsList);

Thats all on the server side.

Clientside:

To make a connection and read the response use the answer of marqss. To get the json into a list use this:

List<ParkingSpot> list = gson.fromJson(json, new TypeToken<List<ParkingSpot>>(){}.getType());


I don't have too much experience with parsing JSON strings but to retrieve a string from the response you can use the following:

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.google.com"); //replace URL to your service

httpResponse = client.execute(request);
HttpEntity entity = httpResponse.getEntity();

if(entity != null){
    InputStream is = entity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    while((line = reader.readLine()) != null){
        sb.append(line + "\n");
    }
    JSONString = sb.toString();
}

You can of course use POST method too.

Hope this helps :D

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜