When i try to run this code in android i am getting the resultant String as "Name":"Text1\/Text2" But the result should be {"Name":"Text1/Text2"}.
try {
String str;
JSONObject json = new JSONObject();
json.put("Name", "Text1/Text2");
str = json.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thanks.
As #GrlHu said that by default the android will convert your string into utf-8 encoding format so your / will be replaced with \/. Please read the following two post 1. JSON: why are forward slashes escaped?
2. Why is the slash an escapable character in JSON?
So instead of this you can use getString(Name) method. Hope you will get the perfect value.
try {
String str;
JSONObject json = new JSONObject();
json.put("Name", "Text1/Text2");
str = json.getString("Name");
Log.e("test", str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
I have such a JSON: https://paste.ubuntu.com/p/HkTK9xTzNx/
How do I get a "imdb_id" String (line 14). There is no array which contains that value,it's not in square branches,so I don't know how to get it.
Solution as per your need:
try {
imdbLink = response.getString("imdb_id");
} catch (JSONException e) {
e.printStackTrace();
}
A standard solution:
String json = "{\"imdb_id\":\"str12345\"}"; // your json response from network call/local file
JSONObject jsonObject;
try {
jsonObject = new JSONObject(json);
String id = jsonObject.getString("imdb_id");
} catch (Exception e) {
e.printStackTrace();
}
I am getting html source from Aozora Bunko. Html file is Shift-JIS encoded. I am trying to get book title and author. Then I want to record title and author into SQLite(UTF-8) database.
String[] splittedResult = result.split("\"title\">");
splittedResult = splittedResult[1].split("</h1>");
String title = splittedResult[0];
byte[] b = null;
try {
b = title.getBytes("Shift_JIS");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String value=null;
try {
value = new String(b, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
...
myDatabase.addBookInformation(value, author);
Result is like this: latin letters are showing normally. But japanese letters are shown by blocks question mark inside (please do not pay attention to null values)
How to solve this problem?
As #Codo pointed out, solution for this problem was before.
I changed this
s = EntityUtils.toString(response.getEntity(), "UTF-8");
to this
s = EntityUtils.toString(response.getEntity(), "Shift_JIS");
And now there is no need for encoding.
String[] splittedResult = result.split("\"title\">");
splittedResult = splittedResult[1].split("</h1>");
String title = splittedResult[0];
/** I HAVE TAKEN THIS PART OF MY CODE
byte[] b = null;
try {
b = title.getBytes("Shift_JIS");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String value=null;
try {
value = new String(b, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
**/
I am new in android.I need to take values from web service.Here i used json parsing.The out put Json format is { "flag": 0 }. Here i need to take the value of flag and using that value i want to start another method. How do i take the value of flag. please help me. I used in this way.
public String objectvalue(String result){
try {
JSONObject obj=new JSONObject(result);
String flag=obj.getString("flag");
mString=flag;
System.out.println(mString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mString;
}
But i didnot get the value of flag.Here argument result is output from the server.ie,result={ "flag": 0 }
First of all, where is the declaration of mString variable? I assume it is declared as instance variable in your java class having this method, if not please check.
You have a well formed JSON in the form of
{ "flag": 0 }
so converting it to a JSONObject should work perfectly.
For extracting value of flag key
There is key named flag in this JSONObject which has an Integer value and you are trying to extract it using getString() method.
You should be using either of the following methods calls
optInt(String key)
Get an optional int value associated with a key, or zero if there is no such key or if th value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.
int flag = optInt("flag");
OR
optInt(String key, int defaultValue)
Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.
int flag = optInt("flag", 0);
Your code with changes
public int objectValue(String result){
int flag = 0;
try {
JSONObject obj=new JSONObject(result);
flag = obj.optInt("flag");
} catch (JSONException e) {
e.printStackTrace();
}
return flag;
}
Edit: Answer to question in comment.
public String objectValue(String result){
int flag = 0;
try {
JSONObject obj=new JSONObject(result);
flag = obj.optInt("flag");
} catch (JSONException e) {
e.printStackTrace();
}
return String.valueOf(flag);
}
Hope this helps.
You may try using AsyncTask for your concern. It's best and preffered way to fetch JSON data
Define AsyncTask like this ..
new BussinessOwnerHttpAsyncTask().execute();
and your AsyncTask class ..
class BussinessOwnerHttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// Progress dialog code goes over here ..
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Maintaining Shared preferences class for further...
HttpClient httpclient = new DefaultHttpClient();
String myUrl = Your_url_goes_over_here;
String encodedURL = "";
try {
encodedURL = URLEncoder.encode(myUrl, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
URL url = new URL(encodedURL);
Log.d("asca", ""+url);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.i("url", city_name + "~" + country_name);
Log.d("location", request_url+encodedURL);
HttpGet httpget = new HttpGet(request_url+encodedURL);
try {
httpresponse = httpclient.execute(httpget);
System.out.println("httpresponse" + httpresponse);
Log.i("response", "Response" + httpresponse);
InputStream is = httpresponse.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String recievingDataFromServer = null;
while ((recievingDataFromServer = br.readLine()) != null) {
Log.i("CHECK WHILE", "CHECK WHILE");
sb.append(recievingDataFromServer);
}
myJsonString = sb.toString();
Log.d("manish", myJsonString);
serverSearchData = sb.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
if (myJsonString.length() > 0) {
try {
myJsonObject = new JSONObject(myJsonString);
String your_flag = myJsonObject.getString("flag");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Now you are good to go with your queries..
{ // JSONObject
"flag": 0
}
Use
JSONObject obj=new JSONObject(result);
int flag=obj.getInt("flag");
http://developer.android.com/reference/org/json/JSONObject.html
public int getInt (String name)
Added in API level 1
Returns the value mapped by name if it exists and is an int or can be coerced to an int.
Throws
JSONException if the mapping doesn't exist or cannot be coerced to an int.
If this does not work you need to post more info.
the "flag" values format at interger, not string, this is simple code to do that :
int flagValues = jsonObject.getInt("flag");
Log.w("values ",String.valuesOf(flagValues));
I got a json response as
{
"tasks": null,
"projects": null
}
how to check if the array has null values and handle the case??
Thanks:)
Try this,
jsonObject.isNull("field-name")
Reference: JSON null handling and this.
Try This
=============
try {
String url;
JSONObject JsonData = new JSONObject("YOUR FULL JSONSTRING");
JSONArray webData = JsonData.getJSONArray("YOUR ROOT NAME OF YOUR JSON RESPONSE");
for(int i=0;i<webData.length();i++)
{
JSONObject TeampObj = webData.getJSONObject(i);
if(TeampObj.getString("tasks").trim().length()>0)
{
//store data in arrylist or string array
}
if(TeampObj.getString("projects").trim().length()>0)
{
//store data in arrylist or string array
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try..
public boolean isNull (String name)
Added in API level 1
Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.
use try ... catch to handle the exception:
Try{
// parsing data
}catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I have an ASP.Net 3.5 Webservice (asmx) that returns what appears to be valid JSON. I have validated the returned JSON using an online validator (JSONLint . com) and it says it is valid. I can not figure out how to parse this string.
{
"d": "{\"returnType\":\"authToken\",\"returnData\":\"b1ec28b8-3fca-427a-bbce-8802fb95d94b\"}"
}
Below is my code.
public static JSONObject DotNetJSONResponse(String raw) throws Exception {
JSONObject joRaw;
try {
joRaw = new JSONObject(raw);
JSONObject joD = joRaw.getJSONObject("d");
return joD;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
try this way
public static JSONObject DotNetJSONResponse(String raw) throws Exception {
JSONObject joRaw;
try {
joRaw = new JSONObject(raw);
String str1 = joRaw.getString("d");
JSONObject joD = new JSONObject(str1);
return joD;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
try this one. In your sample response, d is a an attribute, not a JSONObject. So have to parse the string first, then convert the d string as a JSONObject.
public static JSONObject DotNetJSONResponse(String raw) throws Exception {
JSONObject joRaw;
try {
joRaw = new JSONObject(raw);
String t=joRaw.getString("d");
System.out.println(t); \\< ----------
JSONObject joD = new JSONObject(t);
return joD;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}