Reputation: 18594
What's the easiest way to retrieve JSON from a web-service and to parse it? Without using any additional plug-ins?
Upvotes: 0
Views: 153
Reputation: 2319
This is the best way to retreive JSON data and parsing it, i have used it in my project and it works totally well. Check out this Tutorial (source code also available). If you are using JSON, you will definitely need Google gson library to convert Java Objects into their JSON representation. You can download it from here.
Upvotes: 2
Reputation: 3147
The code below should give you a starting point, just use it in an activity/service class. Its gets data from a URL (webservice), and converts it into a JSON object you can use.
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(***Put your web service URL here ***)
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
//Turn string JSON into object you can process
JSONArray jsonArray = new JSONArray(stringBuilder.toString());
for (int i = 0; i < jsonArray.length(); i++)
{
//Get Each element
JSONObject jsonObject = jsonArray.getJSONObject(i);
//Do stuff
}
Upvotes: 0
Reputation: 6172
You should have a look here: http://code.google.com/p/android-query/wiki/AsyncAPI
Everything is explained, with the code samples you need.
Upvotes: 0
Reputation: 68167
If you want the standard procedure then you need to use JSONObject
and JSONArray
to parse responses. However, it is fuzzy and cumbersome when your response string contains a complex structure. In order to deal such complex responses its better to off the parsing to Gson, Jackson or any other library.
Upvotes: 0