I have been following a tutorial and finally have understand to a decent degree using AsyncTask and how to send an http get request to get the json returned. I can get the json, I think successfully but am having trouble parsing it.
The tutorial I was looking at uses a pretty simple weather api which sends back pretty easy json to parse.
Mine is a search result with info on each item. My json looks like this:
http://pastebin.com/f65hNx0z
I realize the difference between json objects and the arrays of info. Just a bit confused on how to parse over to get information on each beer and the brewery info.
My code below:
String jsonUrl = url + query;
Toast.makeText(this, jsonUrl, Toast.LENGTH_SHORT).show();
//todo: get json
new ReadJSONResult().execute(jsonUrl);
return false;
}
private class ReadJSONResult extends AsyncTask
<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
///code below is what I kow I need to reconstruct and change to parse
JSONObject jsonObject = new JSONObject(result);
JSONObject weatherObservationItems =
new JSONObject(jsonObject.getString("weatherObservation"));
Toast.makeText(getBaseContext(),
weatherObservationItems.getString("clouds") +
" - " + weatherObservationItems.getString("stationName"),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
}
You should use a JSON deserializer library to object which supports nested objects, also. I recommend Gson https://code.google.com/p/google-gson/
There is a Java class generator from JSON response. jsongen.byingtondesign.com will parse your json response and give you Java Bean class. which will help you to understand the need.
Related
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to display information retrieved from server using php in an android app,I have retrieved the information in a String with json formatting here is the retrieve code and php code.
PHP code
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
//Getting values
$username = $_POST['username'];
require_once('dbConnect.php');
$sql = "SELECT * FROM `employee` WHERE username='$username'";
$result=mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
echo json_encode($row);
}
Android Retrieve code
#Override
protected String doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
HashMap<String,String> params1= new HashMap<>();
params1.put(Config.KEY_EMP_UN,mUsername);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Config.URl_RET, params1);
return res;
// TODO: register the new account here.
}
#Override
protected void onPostExecute(final String success) {
Toast.makeText(Main2Activity.this,success,Toast.LENGTH_LONG).show();
final TextView Textview1 = (TextView)findViewById(R.id.textView);
Textview1.setText(success);
}
This retrieves info in format shown in below image
What is want to do is extract Name,Designation,Salary,Password and display them in separate TextView.How can I do that?
Take your server response and parse it like this
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("name")) {
String name=jsonObject.getString("name");
}
if (jsonObject.has("designation")) {
String designation=jsonObject.getString("designation");
}
if (jsonObject.has("salary")) {
int salary=jsonObject.getInt("salary");
}
if(jsonObject.has("password")){
String password=jsonObject.getString("password");
}
}catch (Exception e) {
}
you have to parse the json :
JSONObject jsonObject=new JSONObject(success);
//key value for eg : name,salary etc
// now do whatever you want to do
jsonObject.getString("your key value");
There are lots of possible duplicates to this question, so I recommend closing this question after reading this answer.
What you have in here is a JSON response and in order to parse information in JSON, you have to use a JSON parser. Libraries like Gson, Jackson, Moshi will be able to do this.
If you're using Gson, you have to generate model classes of the response which can be written manually or auto-generated using jsonschema2pojo. Once Gson parses your JSON, you can use your model classes getters to access data.
Links to tutorials
https://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
Youtube video
https://www.youtube.com/watch?v=y96VcLgOJqA
I am using web services in my application. I use REST services. When I call the web service I get a 200 Response code and correct json response too. But sometimes I get a 200 response code along with an non-json response. So before parsing I need to check whether its a valid json or not. Pls help me.
You can check Json String with the help of following method,
public boolean isJSONValid(String json)
{
try
{
new JSONObject(json);
return true;
}
catch(JSONException ex)
{
return false;
}
}
Use try catch block. Like this:
try {
JSONObject jsonObject = new JSONObject("yourjsonstring");
}
catch(JSONException j) {
System.out.println("Not a JSON");
}
This is part of an AsyncTask that calls a web service that returns a JSON result. As you can see I hard coded the actual JSON return object. This was pulled directly from the error I got that specified it could not create the JSON object from the string object I was passing in, which is the variable result. That error occured when it hit new JSONObject(result) in the ParseResults method. Why would hard coding the exact string work but not the string being passed in?
#Override
protected void onPostExecute(String result) {
try {
result = "{\"Response\":{\"ReturnCode\":200,\"ReturnMessage\":\"Information Successfully Retrieved\",\"ReturnData\":null,\"ReturnClass\":{\"PRO_ID\":\"11111111-1111-1111-1111-111111111111\",\"PRO_FirstName\":\"SILVER\",\"PRO_LastName\":\"HIYO\"},\"FriendlyErrorMessage\":null}}";
JSONObject jsonObject = new ApiMethods().ParseResult(result);
ParseResults method snippet.
public JSONObject ParseResult(String result) throws JSONException
{
JSONObject returnedObject = new JSONObject();
try
{
JSONObject jsonObject = new JSONObject(result);
Also below, as i stated in a comment to another user, is the return statement that is returning the data. This is being returned from a .NET MVC application. I added in the UTF8 when that was mentioned and still get the same error.
return Json(data: new { Response = returnValue }, contentType: "application/json", contentEncoding: System.Text.Encoding.UTF8, behavior: JsonRequestBehavior.AllowGet);
And the entire error message:
org.json.JSONException: Value {"Response":{"ReturnCode":200,"ReturnMessage":"Information Successfully Retrieved","ReturnData":null,"ReturnClass":{"PRO_ID":"11111111-1111-1111-1111-111111111111","PRO_FirstName":"Silver","PRO_LastName":"HIYO"},"FriendlyErrorMessage":null}} of type java.lang.String cannot be converted to JSONObject
Seems like your hardcoded json object is not a valid json object. This may be the reason why it throws exception. Check validitiy of json object here first.
type java.lang.String cannot be converted to JSONObject
This means "Use getString() for String"
getJSONObject() may cause this error.
class Response {
String returnMessage;
...
}
Response response;
response.returnMessage= "msg";
JSONObjct obj;
obj = response.getJSONObject("ReturnMessage"); // cannot be converted
It maybe a encoding problem. Browser (and source editor) may have converted the result string encoding.
Q: ... I am storing items for the JSON data as Strings which is resulting in some odd character appearing
A: new String(jo.getString("name").getBytes("ISO-8859-1"), "UTF-8");
Android JSON CharSet UTF-8 problems
Hard coded JSON string is valid. If you want to try, replace (\") with (") and paste it to the checker.
{
"Response": {
"ReturnCode": 200,
"ReturnMessage": "Information Successfully Retrieved",
"ReturnData": null,
"ReturnClass": {
"PRO_ID": "11111111-1111-1111-1111-111111111111",
"PRO_FirstName": "SILVER",
"PRO_LastName": "HIYO"
},
"FriendlyErrorMessage": null
}
}
JSON object is like a structure (or class)
It looks like this.
class Response {
int ReturnCode = 200;
String ReturnMessage = "Information Successfully Retrieved";
...
}
Sample code.
protected void onPostExecute(String result)
{
JSONObject jsonObject;
JSONObject response;
int returnCode;
String returnMessage;
//JSONObject returnMessage;
result = "{\"Response\":{\"ReturnCode\":200,\"ReturnMessage\":\"Information Successfully Retrieved\",\"ReturnData\":null,\"ReturnClass\":{\"PRO_ID\":\"11111111-1111-1111-1111-111111111111\",\"PRO_FirstName\":\"SILVER\",\"PRO_LastName\":\"HIYO\"},\"FriendlyErrorMessage\":null}}";
try
{
jsonObject = new JSONObject(result);
response = jsonObject.getJSONObject("Response");
returnCode = response.getInt("ReturnCode");
returnMessage = response.getString("ReturnMessage");
//returnMessage = response.getJSONObject("ReturnMessage"); // This may cause same error
}
catch (JSONException e)
{
e.printStackTrace();
}
}
Use this site to validate your json string
http://jsonlint.com/
I'm a beginner in android programming.So,I have no idea how to check my login by using PHP. NullPointerException is also appear.I don't know what should I do.Please help for login code.
That's my Jason code.
public void jsonen()
{
ArrayList<NameValuePair> pp = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userID","409"));
String result = response.toString();// store the result returned by PHP script that runs MySQL query
Log.i("response", response);
try{
JSONObject jArray = new JSONObject (result);
for(int i=0;i<jArray.length();i++){
int status = jArray.getInt("requestStatus");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
The code looks ok (looks horrible actually - well to many if statements and the goto mixed in) and I can't see anything obvious on a php side.
You are using global function db_connect() so make sure that this returns a link to DB.
Other then that you want to read about sql injection:
http://php.net/manual/en/security.database.sql-injection.php
Purely as an academic exercise I wanted to convert one of my existing GAE applets to return the response back to Android in JSON and parse it accordingly.
The original XML response containing a series of booleans was returned thus:
StringBuilder response = new StringBuilder();
response.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
response.append("<friend-response><added>");
response.append(friendAdded);
response.append("</added><removed>");
response.append(friendRemoved);
response.append("</removed><found>");
response.append(friendFound);
response.append("</found></friend-response>");
I want to replace this with a JSON response that looks something like this:
{ "friendResponse" : [ { "added":true, "removed":false, "found":true } ]}
I think I can generate the array contents as follows (I haven't tested it yet) but I don't know how to create the top-level friendResponse array itself. I can't seem to find any good examples of creating JSON responses in Java using the com.google.appengine.repackaged.org.json library. Can anyone help put me on the right path?
boolean friendAdded, friendRemoved, friendFound;
/* Omitted the code that sets the above for clarity */
HttpServletResponse resp;
resp.setContentType("application/json");
resp.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
try {
//How do I create this as part of a friendResponse array?
json.put("added", friendAdded);
json.put("removed", friendRemoved);
json.put("found", friendFound);
json.write(resp.getWriter());
} catch (JSONException e) {
System.err
.println("Failed to create JSON response: " + e.getMessage());
}
You need to use JSONArray to create the (single-element) array that will store your object:
try {
JSONObject friendResponse = new JSONObject();
friendResponse.put("added", friendAdded);
friendResponse.put("removed", friendRemoved);
friendResponse.put("found", friendFound);
JSONArray friendResponseArray = new JSONArray();
friendResponseArray.put(friendResponse);
JSONObject json = new JSONObject();
json.put("friendResponse", friendResponseArray);
json.write(resp.getWriter());
} catch (JSONException e) {
System.err
.println("Failed to create JSON response: " + e.getMessage());
}
You can use GSON: https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples
With this framework, you can serialize an object to json, and vice versa.