I created a json result in mvc and I'm building an Android app to get the json result. This is what my json result looks like
{"name":"Mr. Spock","gender":"Male"}
This is my controller
public ActionResult Index()
{
var result = new { name = "Mr. Spock", gender = "Male" };
return Json(result, JsonRequestBehavior.AllowGet);
}
And this I'm using in android
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
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;
}
}
I have a declared variable url. Every time I debug, the json variable does not have any values and says "errors during the evaluation"
Anyone with a tip? I tried working with Gson, but no succes
Kind regards
I'll give you some code for Gson. It really is much easier to work with than the built in JSON parsing code. Here's a minimal example using your JSON.
Person.class:
package com.example.tutorial.models;
import com.google.gson.annotations.SerializedName;
public class Person {
#SerializedName("gender")
public String gender = "";
#SerializedName("name")
public String name = "";
}
The annotations are really only necessary when your variable and JSON name differ, but I tend to always include them as it reinforces that they are coming from JSON.
To deserialize:
Gson gson = new GsonBuilder().create();
Person person = gson.fromJson(json, Person.class);
It really is that simple. If this does not work, log the result from the web server and make sure it really is the valid JSON string you expect it to be.
I do have one question, where is your AsyncTask? Your attempt to open a connection to the webserver in the UI thread will definitely cause a NetworkOnMainThreadException. I created a library to do RESTful calls on Android. It's licensed under BSD, so feel free to use it as a guide or outright use it: https://github.com/nedwidek/Android-Rest-API
Related
I've been trying to figure out how to handle the json response from a GET request. This is the code I have for the request:
String urlString = URL I want to request;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
String response = getStringFromInputStream(is);
My question is what to do now. I've been playing with gson but I cannot figure out how to parse the response for the required information.
I also found this method somewhere online to turn the response into a string:
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
If anyone could help me parse the string or somehow otherwise handle the response I'd really appreciate it.
You can use Jackson framework to parse the response into Java Object. Once you add the dependency, this is how it will work:
Let's say you are getting the below response from the API:
{
"id": 1,
"name": "foo"
}
You can write the following code to deserialise it into an Object:
public class Response {
private int id;
private String name;
//Getters and Setters
}
//code to convert
String response = sb.toString();
ObjectMapper mapper = new ObjectMapper();
Response responseObject = mapper.readValue(response, Response.class);
If the json is not valid, it will fail and throw JsonParseException or JsonMappingException. You can handle it in your code and respond accordingly.
Here's step by step tutorial on how to use Jackson.
It depends on the what you want to do with Json.I am assuming you want to convert in into an Java object.
For that you can use Gson or Jackson.
Suppose you have a json like
{"userId":"1","userName":"Yasir"}
and your java class like
class User{
int userId;
String userName;
//setters and getters
}
then you can use something like
Gson gson = new Gson();
User user= gson.fromJson(jsonInString, User.class);
to create java object.
Hi I am new to android programming and I am working on a project that converts a list into json object and stores it in the server and retrieves it. I am able to send the json object to the server and store it but i am not able to retrieve it. What approach should i use to retrieve the json object stored on the server?
You can reffer bellow class ...... call getJSONfromURL(YOUR_JOSN_URL) and method will return you JSONObject.
I hope this will work
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
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, "UTF-8"), 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;
}
}
To retrieve JSON from server you have to establish a connection with server first by using DefaultHttpClient Hope you did that. If yes, post your code and if no then have look on
www.androidhive.info/2012/01/android-json-parsing-tutorial
Or google it you will lot of help to parse the JSON when you have URL with you.
I'm trying to parse JSON data which is coming from this url.
But I am getting these errors:
03-27 16:48:21.019: E/Buffer Error(23717): Error converting result java.lang.NullPointerException
03-27 16:48:21.059: E/JSON Parser(23717): Error parsing data org.json.JSONException: End of input at character 0 of
Wwhen I debug my code; getJsonFromUrl() method returns null jobject. Here is the JSONParser class which I used. What's causing the error?
public class JSONParser {
static InputStream iStream = null;
static JSONArray jarray = null;
static JSONObject jObj= null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
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");
}
iStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parsing the string to a JSON object
try {
if (json != null) {
jObj = new JSONObject(json);
} else {
jObj = null;
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I'm making the call for this method from another class using these lines. (url parameter is defined at top)
JSONParser jParser = new JSONParser();
final JSONObject jobject = jParser.getJSONFromUrl(url);
You are trying to get the JSON content using a HTTP POST method instead of the appropiated GET method (W3schools.com GET vs.POST), modify your source code to simplify and fix your HTTP request
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(get);
String json = EntityUtils.toString(httpResponse.getEntity());
System.out.println(json);
....
....
} catch (Exception e) {
....
}
I have to download more than 40,000 json records from my web service, but it is taking so long time to download. The downloaded data is storing into a string, but I am not able parse that string. Please tell me a solution to solve this problem.
URL: https://buzoonga.co.uk/appapi/contacts.php?user_id=531
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;
}
check out gzip. excellent text compressor. you are going to remove ~70% of the size :) you just have to gzip it serverside and unzip it clientside. if this overhead increases the time but the download is a third of the time, you might win in the end.
Also consider designing a better schema to reduce the size of your jsons.
Like, instead of "animalBodyParts" put "abp" or something. you have not put an example of your jsons so I am just guessing.
You can use the JSONTokener class and pass the InputStream
jObj = new JSONObject(new JSONTokener(httpEntity.getContent()));
To reduce the time to download you need to support gzipped downloads on the server side or change your JSON structure to a more compact array based format
Guys can you help me a little bit, Im getting this error:
"JSONException: Value <!DOCTYPE of type java.lang cannot be converted to JSONObject"
When I'm parsing the data here is my code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Here is the code where I'm instantiating the Parser:
private void fillSpinnerCabTypes() {
List<String> cabTypesSpinner = new ArrayList<String>();
JSONParser jsonParser = new JSONParser();
JSONObject cabTypesObject = jsonParser.getJSONFromUrl(urlTypeCabs);
try{
TypesArray = cabTypesObject.getJSONArray(TAG_TYPES);
for(int i = 0; i < TypesArray.length(); i++){
JSONObject c = TypesArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
cabTypesSpinner.add(name);
}
}catch(Exception e ){
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cabTypesSpinner);
final Spinner spnCabTypes = (Spinner)findViewById(R.id.spnTypeOfCab);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spnCabTypes.setAdapter(adapter);
}
I'm really stuck with this. I'm populating the spinner from a database in a backend on Django in the server.
This is my JSON data
{"Types": [{"name": "Normal"}, {"name": "Discapacitados"}, {"name": "Buseta"}]}
This issue comes from the server.
The URL you're requesting, send you back data but not in the JSON format.
The Exception you get is telling you that the String the server send you back starts with:
<!DOCTYPE
This can be:
A simple webpage (instead of raw JSON). It correspond to the first XML tag of a web page (source)
An error page generated by the server, and printed in HTML
To debug this further, simply print the content of your json variable in the logcat:
Log.d("Debug", json.toString());
jObj = new JSONObject(json);
This problem came in my code also.and solution was different.It occured due to spelling mistake of webservice.
Solution 1:
for example real the url is
http://example.com/directory/file.php
and i had used
http://example.com/directory/file1.php
Solution 2:
use loopj library .it exactly gives you the explained error.
AsyncHttpClient client = new AsyncHttpClient();
client.post(str , localRequestParams, new AsyncHttpResponseHandler() {
#Override
public void onFinish() {
super.onFinish();
Log.i("onFinish","onFinish");
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.i("onSuccess","onSuccess");
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.i("onFailure","onFailure");
}
});