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;
}
Related
When trying to retrieve the response json from my api I can only ever get a string value which I am unable to convert to jsonobject to use.
Should respond with json format {"result":"success","client[id]":"1"}
But I am only able to retrieve string "result=success,client[id]=1"
public void createWHMCSUser(final String emailID, final String random, final String uid) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String e = URLEncoder.encode(emailID, "utf-8");
String r = URLEncoder.encode(random, "utf-8");
URL url = new URL("http://create.user.com/includes/api.php?action=AddClient&username=abc123&password=abc123&accesskey=abc123&firstname=User&lastname=Name&email=" + e +"&address1=na&city=na&state=na&poscode=00000&country=US&phonenumber=0000000000&password2=" + r + "&reponsetype=json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept","application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
if(conn.getResponseCode() == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String readAPIResponse = " ";
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = in.readLine()) != null){
jsonString.append(readAPIResponse);
JSONObject obj = new JSONObject(jsonString.toString());
int aJsonString = obj.getInt("Client[id]");
SetClientID(uid,aJsonString);
}
in.close();
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
use this way more easier and fast
for more examples and to built library check this :
enter link description here
AndroidNetworking.get("URL")
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
// handle your response here
}
#Override
public void onError(ANError error) {
// handle error
}
});
Use the json library to add the java object to JSONObject. That will store all the java object content in to json string format in your server code. That will convert In to json format.
Then you will return the code from server as the regular string.
In the client side, you will receive it as the string.
Then you need to convert it to java object from the json string. That is the actual json string. You will e able to convert that string to java obj.
But what you have return is not the json String. That is just string only.
I have written a webservice which consumes form param as given below
#POST
#Path("/upload/")
#Consumes("multipart/form-data")
#Produces("text/plain")
public String upload(#FormDataParam("model") InputStream modelInputStream,
#FormDataParam("file") InputStream fileInputStream) {
JsonObject userDefinedObj = new JsonObject();
try {
Scanner s = new Scanner(fileInputStream).useDelimiter("\\A");
Scanner modelText = new Scanner(modelInputStream).useDelimiter("\\A");
String modelName = modelText.hasNext() ? modelText.next() : "";
String result = s.hasNext() ? s.next() : "";
String delimiter = "";
if (result.contains("\r\n"))
delimiter = "\r\n";
else if (result.contains("\n\r"))
delimiter = "\r\n";
else if (result.contains("\n"))
delimiter = "\n";
else if (result.contains("\r"))
delimiter = "\r";
String[] deviceList = result.split(delimiter);
userDefinedObj = new JsonParser().parse(modelName).getAsJsonObject();
String serverName = userDefinedObj.get("serverName").getAsString();
String serverUrl = getServerUrlFromServerName(serverName);
userDefinedObj.remove("serverName");
JsonArray eventsArray = new JsonArray();
for (int i = 0; i < deviceList.length; i++) {
JsonObject eventObject = new JsonObject();
JsonObject deviceObj = new JsonObject();
JsonObject idTypeDefinitionsObj = new JsonObject();
JsonArray appEventListArray = new JsonArray();
String platform = userDefinedObj.get("appPlatform").getAsString();
String operatingSystem = platform.equalsIgnoreCase("UNKNOWN") ? "UNKNOWN" : "";
JsonElement operatingSystemObj = new JsonParser().parse(operatingSystem);
JsonElement deviceIdObj = new JsonParser().parse(deviceList[i]);
deviceObj.add("operatingSystem", operatingSystemObj);
deviceObj.add("deviceId", deviceIdObj);
JsonElement idTypeObj = new JsonParser().parse("DEVICE_ID");
JsonElement alternateIdListObj = new JsonNull();
idTypeDefinitionsObj.add("idType", idTypeObj);
idTypeDefinitionsObj.add("idValue", deviceIdObj);
idTypeDefinitionsObj.add("alternateIdList", alternateIdListObj);
eventObject.add("device", deviceObj);
eventObject.add("idTypeDefinitions", idTypeDefinitionsObj);
eventObject.add("appEventList", appEventListArray);
eventsArray.add(eventObject);
}
userDefinedObj.add("events", eventsArray);
String url = "http://" + serverUrl + "/url/url11/events";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
writer.write(userDefinedObj.toString());
writer.close();
int responseCode = con.getResponseCode();
return String.valueOf(responseCode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "400";
}
Now I am writing a Junit test case which should pass data to this webservice. I tried using the below code. But I am getting error 415
#Test
public void postEvents() {
try {
String url = "http://url/url2/upload";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
String requestPayload = "{\"accessToken\":\"abcdefg\"}";
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
writer.write(requestPayload);
writer.close();
int responseCode = con.getResponseCode();
assertTrue(responseCode == 200);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
System.out.println(response.toString());
AccessToken token = gson.fromJson(response.toString(), AccessToken.class);
String tokenValue = token.getTokenValue();
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
Actually I wanted to pass a csv file and add the below data along with it.
Model
{
"accessToken":"abcdefg",
"serverName":"SIT",
"appPlatform":"UNKNOWN",
"appBundleId":"com."
}
form-data; name="file"; filename="aa10.csv"
I have no idea how to do it and I browsed yesterday whole day and couldn't get a related link. Any help would be much appreciated. Thanks in advance.
Just in case someone sees this answer in the future I resolved this issue by adding jersey client jar file as maven dependency. Then in the Junit test case I did the following
ClientConfig config = new DefaultClientConfig();
config.getClasses().add(MultiPartWriter.class);
Client client = Client.create(config);
WebResource resource = client.resource(
"http://localhost:8080/url/url11/upload");
InputStream is = App.class.getClassLoader().getResourceAsStream("aa10.csv");
String exampleString = "{\"accessToken\":\"324d393c-f564-4699- ae53-8fdcfc7b8fe6\",\"serverName\":\"SIT\",\"appPlatform\":\"UNKNOWN\",\"appBundleId\":\"com.\"}";
InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));
FileDataBodyPart filePart = new FileDataBodyPart("file",
new File("/Users/user/Documents/aa10.csv"));
FormDataMultiPart multipartEntity = (FormDataMultiPart) new FormDataMultiPart()
.field("model", exampleString, MediaType.MULTIPART_FORM_DATA_TYPE).bodyPart(filePart);
ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class,
multipartEntity);
Now the issue got resolved and I am getting the expected response
Here is a sample of my json_encode in PHP:
print(json_encode($row));
leads to {"AverageRating":"4.3"} which is good.
But in Java, I can not seem to grab this 4.3 value. Here it is (for an Android project) I have edited non-relevant data.
public class Rate extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
String Item, Ratings, Review, starAvg;
RatingBar ratingsBar;
ArrayList<NameValuePair> param;
public void onCreate(Bundle savedInstanceState) {
starAvg = "0"; // Sets to 0 in case there are no ratings yet.
new starRatingTask().execute();
ratingsBar = (RatingBar) findViewById(R.id.theRatingBar);
class starRatingTask extends AsyncTask<String, String, Void> {
InputStream is = null;
String result = "";
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.---.com/---/average_stars.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("item", Item));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
String starAvgTwo = null;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
starAvg = json_data.getString("AverageRating");
starAvgTwo = starAvg;
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Star Ratings!",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
Toast.makeText(getBaseContext(), starAvgTwo,
Toast.LENGTH_LONG).show();
ratingsBar.setRating(Float.valueOf(starAvg));
}
}
That second toast produces a blank (I assume a "" - empty string?). If I change the toast variable back to starAvg, then it toasts "0".
How can I retrieve the value of 4.3.
As we discussed in the comments on the original question, the PHP is sending down as single JSONObject rather than an array. Parsing as a JSONObject is required in it's present state; however, if you begin sending down an array of your value objects, then you'd use JSONArray to parse it.
I think your JSON doesn't contain array. so just do this:
JSONObject jsonObject = new JSONObject(result); //to convert string to be a JSON object
String averageRating = jsonObject.getString("AverageRating"); //get the value of AverageRating variable
and try toast the averageRating.
and how to get the array from JSON object?
if you have JSON:
{"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }]
}
then use this code
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(Rate.class.getName(), jsonObject.getString("firstName"));
}
that code will produce
John Anna Peter
in your LogCat
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
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