Parsing JSON from URL - java

Is there any simplest way to parse JSON from a URL? I used Gson I can't find any helpful examples.

First you need to download the URL (as text):
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
Then you need to parse it (and here you have some options).
GSON (full example):
static class Item {
String title;
String link;
String description;
}
static class Page {
String title;
String link;
String description;
String language;
List<Item> items;
}
public static void main(String[] args) throws Exception {
String json = readUrl("http://www.javascriptkit.com/"
+ "dhtmltutors/javascriptkit.json");
Gson gson = new Gson();
Page page = gson.fromJson(json, Page.class);
System.out.println(page.title);
for (Item item : page.items)
System.out.println(" " + item.title);
}
Outputs:
javascriptkit.com
Document Text Resizer
JavaScript Reference- Keyboard/ Mouse Buttons Events
Dynamically loading an external JavaScript or CSS file
Try the java API from json.org:
try {
JSONObject json = new JSONObject(readUrl("..."));
String title = (String) json.get("title");
...
} catch (JSONException e) {
e.printStackTrace();
}

GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).
This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.
Only three lines of relevant code.
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
public class GsonFetchNetworkJson {
public static void main(String[] ignored) throws Exception {
URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyDto dto = new Gson().fromJson(reader, MyDto.class);
// using the deserialized object
System.out.println(dto.headers);
System.out.println(dto.args);
System.out.println(dto.origin);
System.out.println(dto.url);
}
private class MyDto {
Map<String, String> headers;
Map<String, String> args;
String origin;
String url;
}
}
If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with curl or other clients) then a possible cause could be that the endpoint expects a User-Agent header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g. System.setProperty("http.agent", "Netscape 1.0");.

You could use org.apache.commons.io.IOUtils for downloading and org.json.JSONTokener for parsing:
JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));

Here is a easy method.
First parse the JSON from url -
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
Then place a task and then read the desired value from JSON -
private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
JSONObject json;
try {
json = new JSONObject(result);
////CREATE A JSON OBJECT////
JSONObject data = json.getJSONObject("JSON OBJECT NAME");
////GET A STRING////
String title = data.getString("");
//Similarly you can get other types of data
//Replace String to the desired data type like int or boolean etc.
} catch (JSONException e1) {
e1.printStackTrace();
}
//GETTINGS DATA FROM JSON ARRAY//
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray postalCodesItems = new JSONArray(
jsonObject.getString("postalCodes"));
JSONObject postalCodesItem = postalCodesItems
.getJSONObject(1);
} catch (Exception e) {
Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
}
}
}
You can then place a task like this -
new ReadPlacesFeedTask()
.execute("JSON URL");

public static TargetClassJson downloadPaletteJson(String url) throws IOException {
if (StringUtils.isBlank(url)) {
return null;
}
String genreJson = IOUtils.toString(new URL(url).openStream());
return new Gson().fromJson(genreJson, TargetClassJson.class);
}

import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.io.FileUtils;
import groovy.json.JsonSlurper;
import java.io.File;
tmpDir = "/defineYourTmpDir"
URL url = new URL("http://yourOwnURL.com/file.json");
String path = tmpDir + "/tmpRemoteJson" + ".json";
remoteJsonFile = new File(path);
remoteJsonFile.deleteOnExit();
FileUtils.copyURLToFile(url, remoteJsonFile);
String fileTMPPath = remoteJsonFile.getPath();
def inputTMPFile = new File(fileTMPPath);
remoteParsedJson = new JsonSlurper().parseText(inputTMPFile.text);

I use java 1.8
with com.fasterxml.jackson.databind.ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Integer value = mapper.readValue(new URL("your url here"), Integer.class);
Integer.class can be also a complex type. Just for example used.

A simple alternative solution:
Paste the URL into a json to csv converter
Open the CSV file in either Excel or Open Office
Use the spreadsheet tools to parse the data

Related

update/create JSON object on button press

im am currently creating a CMS applicationa and i am trying to create a JSON object that i can post to my API but i have no idea on how to do this because im new to android. does anyone have an Idea?
My code:
String URL = "http://test.soundwave.drieo.nl/api/content/" + uid + "?apikey=aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
try {
APIClientJSONObject api = new APIClientJSONObject();
JSONObject result = null;
try {
result = api.execute(URL).get();
} catch (Exception e) {
e.printStackTrace();
}
try {
String content = result.optString("FormattedName");
String content2 = result.optString("Title");
String content3 = result.optString("Subtitle");
String content4 = result.optString("Text");
EditText name = (EditText) findViewById(R.id.etInternNaam);
name.setText(content);
EditText titel = (EditText) findViewById(R.id.etName);
titel.setText(content2);
EditText ondertitel = (EditText) findViewById(R.id.etOndertitel);
ondertitel.setText(content3);
EditText EditText = (EditText) findViewById(R.id.etTekst);
EditText.setText(Html.fromHtml(content4));
if("null" == content) {
name.setText("");
}
if("null" == content2) {
titel.setText("");
}
if("null" == content3) {
ondertitel.setText("");
}
if("null" == content4) {
EditText.setText("");
}
} catch (Exception e) {
e.printStackTrace();
}
API code:
package nl.drieo.soundwave.test.cms;
import android.os.AsyncTask;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
/**
* Created by r.devries on 14-3-2016.
*/
public class APIClientJSONObject extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... params) {
JSONObject result = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = new JSONObject(builder.toString());
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
you can create JSONObject like this and put your data into that:
JSONObject json = new JSONObject();
json.put("user", "example");
after putting your data to json, you can pass the json to the 'APIClientJSONObject' class by this way:
EDIT: use this code in to OnClickListener for your Button
try {
result = api.execute(URL,json.toString()).get();
} catch (Exception e) {
e.printStackTrace();
}
and you can get Json in 'APIClientJSONObject' class like this:
JSONObject jsonObject = new JSONObject(params[1])
or if you want 'POST' this json to the webservice, you can use: EDIT: use this in to the APIClientJSONObject class in doInBackground method:
HttpPost httpost = new HttpPost(params[0]);
StringEntity stringentity = new StringEntity(params[1]);
httpost.setEntity(stringentity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
httpclient.execute(httpost, responseHandler);
I hope these code are useful for you.

parse json data coming from webservice in java

I am developing android app where I am getting web-service data as:
"[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"}]"
Now I want to parse this data in json I used replaceAll() function to replace backslashes from the string like this:
String jsonFormattedString = line.replaceAll("\\\\", "");
But I think this method isnot good to work with because it removes all the backslashes from the string which creates problems like I recieved json node like:
"[{\"ID\":9617,\"Text\":\"1 1\/4\\\" PVC\/GI CLAMPS\"}]"
where the string value for Text contains double quotes within string which creates problem for me. So my question is what is the best way to parse this json data in java.
My full json data returned by webservice is as:
"[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"},{\"ID\":53,\"Text\":\"Kanix City\"},{\"ID\":54,\"Text\":\"KANIX DREAM CITY\"},{\"ID\":59,\"Text\":\"KANIX DREAM CITY -- PHASE II\"},{\"ID\":62,\"Text\":\"KANIX DREAM CITY PHASE I\"},{\"ID\":55,\"Text\":\"Kishor_TEST\"},{\"ID\":63,\"Text\":\"Next Generation Housing\"},{\"ID\":65,\"Text\":\"Nothing Job\"},{\"ID\":56,\"Text\":\"PAVAN_TEST\"},{\"ID\":46,\"Text\":\"PRODUCTION UNITS\"},{\"ID\":1,\"Text\":\"PROJECT-01(TYPE 1)\"},{\"ID\":3,\"Text\":\"PROJECT-02(TYPE 1)\"},{\"ID\":5,\"Text\":\"PROJECT-03(TYPE 1)\"},{\"ID\":6,\"Text\":\"PROJECT-04(TYPE 1)\"},{\"ID\":7,\"Text\":\"PROJECT-05(TYPE 1)\"},{\"ID\":8,\"Text\":\"PROJECT-06(TYPE 1)\"},{\"ID\":2,\"Text\":\"PROJECT-07(TYPE 2)\"},{\"ID\":4,\"Text\":\"PROJECT-08(TYPE 2)\"},{\"ID\":9,\"Text\":\"PROJECT-09(TYPE 3)\"},{\"ID\":10,\"Text\":\"PROJECT-10(TYPE 3)\"},{\"ID\":11,\"Text\":\"PROJECT-11(TYPE 4)\"},{\"ID\":57,\"Text\":\"Reviera Classic\"},{\"ID\":43,\"Text\":\"ROAD PROJECT\"},{\"ID\":41,\"Text\":\"SAMPLE PROJECT 1\"},{\"ID\":42,\"Text\":\"SAMPLE PROJECT 2\"},{\"ID\":52,\"Text\":\"Shailesh Test project#1000\"},{\"ID\":61,\"Text\":\"VISHAL PARADISE\"},{\"ID\":60,\"Text\":\"WTC\"}]"
my full code is like this:
#Override
protected List<CItem> doInBackground(String... params) {
try {
String line="";
String ur = "http://"+ServerDetails.hostServer+"/appservices.svc/Projects?Keyword=" ;
lstItm=new ArrayList<CItem>() ;
// Replace it with your own WCF service path
URL json = new URL(ur);
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
line = reader.readLine();
Log.d("LINE",line);
JSONArray array=new JSONArray(line);
Itm=new CItem( "-1", "Select Project" );
lstItm.add(Itm);
for(int i=0; i < array.length(); i++) {
JSONObject tmpJson=array.getJSONObject(i);
Itm=new CItem(tmpJson.getString("ID"),tmpJson.getString("Text"));
lstItm.add(Itm);
}
return lstItm ;
}
catch(Exception e)
{
Log.d("ERRROR--->",e.getMessage());
}
return lstItm ;
}
#mubu9082 ..you dont need to remove these backslashes...
as this json string is shown with backslashes in log or by debugger..
just parse it as usual
public void jsonParser()
{
ArrayList<> list=new ArrayList<>(); //declare this as global
String responseString="[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"}]";
JSONArray array=new JSONArray(responseString);
String id[]=new String[array.length()];
String text[]=new String[array.length()];
for(int i=0;i<array.length();i++)
{
JSONObject tmpJson=array.getJSONObject(i);
id[i]=tmpJson.getString("ID");
text[i]=tmpJson.getString("TEXT");
CItem Itm=new CItem(tmpJson.getString("ID"),tmpJson.getString("Text")); lstItm.add(Itm);
list.add(Itm);
}
}
do this to get response from server
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL ...use
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
HttpEntity entity = httpResponse.getEntity();
String response= EntityUtils.toString(entity);
//pass this response to JSONArray object
//save response and then flush the entity.
entity.consumeContent();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
pass this response to JSONArray object
public InsuranceDO getInsuranceData1(Context context) {
String urlStr = "http://192.168.2.11:8080/Service/category/sample";
InsuranceDO insuranceDO = new InsuranceDO();
HttpURLConnection urlConnection;
List<InsuranceDO> insList = new ArrayList<InsuranceDO>();
try {
String reqVal = "T=421D84EAC8DEB4878CE48C8A0CB870791EB96FE51C7800A8806032A8CE69A4966D87FFA2E139EE6586C1924F9BD070154CB7E8F92985AC6674B0AD37D9F3FC1ED7B2E4C2D01E5525DCE5E6FCDA26AF890633011894AA2B72604CC8B046E4F9C37DE9A61EECD7000325D3EC673E8609AAD753C52B9BC002C014BC18A35AA8AB3636C237088A08EEED72A7C5F2EDE60155E9111A6F74F082C0E4B45D484C00CA5AD5B3560B8A10D47616E48077EBDE490E&UserCode=172278&DBSource=bali";
URL url = new URL(urlStr);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(reqVal.getBytes());
outputStream.flush();
int code = urlConnection.getResponseCode();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder result = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
/**
* To parse json to list data
*/
JSONArray jsonArray = new JSONArray(result.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
insuranceDO.setAgeing(jsonObject.getString("xxx"));
insuranceDO.setInsuredName(jsonObject.getString("yyyy"));
insuranceDO.setProposalNumber(jsonObject.getString("zzzz"));
insuranceDO.setReason(jsonObject.getString("aaaa"));
insList.add(insuranceDO);
}
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Toast.makeText(context, insList.toString(), Toast.LENGTH_LONG).show();
return insuranceDO;
}

PHP $_POST is empty or null

I'm desperately trying to solve an issue with my android app. I submit a List to my server with an enum set as a 'tag'. The PHP pages should look at this tag and then proceed to perform the associated functions and return as a json array or object. This works fine with one version of the app but a cloned version fails to fetch data. The PHP just jumps straight over tag checking at the isset tag and tag is not empty conditions so it must be flat out seeing an empty POST or the object I submit doesn't meet some requirement I'm unaware of.
I've looked through so many posts and searched and searched but haven't found a solution. Why would it work for one version of the app but not for the upgraded version, that hasn't made any changes to the methods used for sending data??
So here's what I'm dealing with. To begin with, an AsyncTask takes the objects and passes to a class that handles communication:
private class UpdateJobList extends AsyncTask<User, Void, Boolean> {
private List<Message> messages;
public UpdateJobList() {
super();
messages = new ArrayList<Message>();
}
#Override
protected Boolean doInBackground(User... params){
try {
CloudConnect cConn = new CloudConnect(sAddress);
this.messages = cConn.getAll(params[0]);
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (true)
{
handleMessageList(messages);
}
}
}
Using the CloudConnect class to get single Json objects or an array of Objects:
public class CloudConnect {
private String site;
private InputStream is;
private Gson gson;
public CloudConnect(String site) throws MalformedURLException {
this.site = site;
this.gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
is = null;
}
public synchronized Message get(Message m) throws IOException {
Message msg = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(this.site);
post.setEntity(new UrlEncodedFormEntity(validateMessage(m)));
HttpResponse response = client.execute(post);
StatusLine status = response.getStatusLine();
if ( status.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
Reader read = new InputStreamReader(is);
String str = (String) gson.fromJson(read, Object.class);
JsonParser parser = new JsonParser();
JsonElement jElem = parser.parse(str);
JsonObject jObject = (JsonObject) jElem;
msg = gson.fromJson(jObject, Message.class);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return msg;
}
public synchronized List<Message> getAll(Message m) throws IOException {
List<Message> mList = new ArrayList<Message>();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(this.site);
post.setEntity(new UrlEncodedFormEntity(validateMessage(m)));
HttpResponse response = client.execute(post);
StatusLine status = response.getStatusLine();
if ( status.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
JsonArray jArray = null;
JsonReader jReader = new JsonReader(reader);
jReader.setLenient(true);
JsonParser parser = new JsonParser();
if (parser.parse(jReader).isJsonArray()){
jArray = parser.parse(jReader).getAsJsonArray();
if ( m instanceof User ){
for (JsonElement je : jArray) {
mList.add(gson.fromJson(je, Job.class));
Log.d("json", je.toString());
}
} else if ( m instanceof Job ) {
for (JsonElement je : jArray) {
mList.add(gson.fromJson(je, Update.class));
Log.d("json", je.toString());
}
}
} else {
JsonElement jElem = parser.parse(jReader);
JsonObject jObject = (JsonObject) jElem;
Error msg = null;
msg = gson.fromJson(jObject, Error.class);
mList.add(msg);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return mList;
}
And the PHP code that checks for the tag:
if ( isset($_POST['messageType']) && $_POST['messageType'] != "") {
$tag = $_POST['messageType'];
//
//various functions depending on messageType tag here. Such as getUser($email).
//functions appear to work fine if the PHP doesn't find the initial conditions
//false and skips them all.
} else {
$response["success"] = 0;
$response["error"]["errorMsg"] = "Tags are null";
$response["error"]["messageType"] = $tag;
$response["error"]["varDump"] = var_dump($_POST);
echo json_encode($response);
}
Ok, now I get it. You do not have a problem on your Android code but in PHP (I came here because of the TAG Android). I am not an expert in PHP, but remember that isset ($ _POST ['messageType']) returns true only if the payload of your POST request contains something like: messageType=some_value. So you need to check if the value that you passsed to post.setEntity(value) is something in this format.
You can use tools like Fiddler to see the payload of your request and debug properly.

android use asynctask to parse json

I am working on android application and I need to parse my json object with data. How you can see I create JSONParser class and try to use asynctask but there is something wrong and I can't understand where is the problem. Every time I use it resultJSON is null. Hope that you can give me an advice!
public class JSONParser {
private String resultJSON;
public JSONArray getJSON(String url) throws JSONException {
Parser parser = new Parser();
parser.execute(url);
return json;
}
private class Parser extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
for (String url : urls) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
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) {
builder.append(line);
}
resultJSON = builder.toString();
} else {
Log.e(JSONParser.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultJSON;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
json = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Why don't you JSONArray json = new JSONArray(resultJSON); do this on post execute method of async task .
And i will not suggest varevarao way , as it will create extra burden of one thread .
You should use the get() method of the AsyncTask class to retrieve the result of the task. It waits for the task to complete and gets the result (which means it'd be best if you enclose it within a separate thread with a progress dialog or just a background thread).
public JSONArray getJSON(String url) throws JSONException {
Parser parser = new Parser();
parser.execute(url);
resultJSON = parser.get(); // Probably put this in a Thread to avoid spending too much time waiting for a result on the main thread
JSONArray json = new JSONArray(resultJSON);
return json;
}
The problem is fixed. It's an awful workaround but it works. Add this line
while(json==null) {}
after calling the execute method.

Using GSON to parse a json datafeed

i have a simple JSON feed which returns an image path, and a set of coordinations. The "coords" can have an unlimited set of coordinations. In my example below it only has 3 set.
{"image":"Some data", "coords": {"0":[0,0], "1":[55,22], "2":[46,65]}}
How would i use GSON to parse this? How do I build the class for this?
Thanks
You're going to have a hard time with that because it's not valid JSON.
http://jsonlint.com/
If it were valid JSON such as ...
{"image":"Some data", "coords": {"0":[0,0], "1":[55,22], "2":[46,65]}}
I believe GSON could parse coords to a map of <String, ArrayList<Integer>> but I'd need to try it to make sure.
Add the gson-1.7.1.jar file and write this class to get the required JSONObject or JSONArray from the url.
public class GetJson {
public JSONArray readJsonArray(String url) {
String read = null;
JSONArray mJsonArray = null;
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = http.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
builder.append(str);
}
is.close();
read = builder.toString();
mJsonArray = new JSONArray(read);
} catch (Exception e) {
e.printStackTrace();
}
return mJsonArray;
}
public JSONObject readJsonObject(String url) {
String read = null;
JSONObject mJsonObject = null;
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = http.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
builder.append(str);
}
is.close();
read = builder.toString();
mJsonObject = new JSONObject(read);
} catch (Exception e) {
e.printStackTrace();
}
return mJsonObject;
}
}
ENJOY...
Then to parse the JSON see the these tutorials,
Tutorial 1
Tutorial 2
Tutorial 3

Categories