problems converting string to JSON - android

Im creating this JSONObject in javascript.
var jsonBack = {id:userID,"dateToday":today, dateYesterday:yesterday,
wbsArrayToday:[{wbs:"13232323"}, {wbs:"13232324"}, {wbs:"13232325"}],
wbsArrayYesterday:[{wbs:"13232333"}, {wbs:"13232334"}, {wbs:"13232335"}]};
Then i call this in my android application.
JSONObject jsonObj = null;
// Henter response data fra server vha. httpResponse
HttpEntity entity1 = response.getEntity();
if (entity1 != null) {
InputStream is = null;
try {
is = entity1.getContent();
// convert stream to string
String result = Converter.convertStreamToString(is);
//Remove []
//if(result.startsWith("["))
// result = result.substring(1, result.length()-1);
// Create JSON Object
jsonObj = new JSONObject(result);
} catch (IllegalStateException e) {
e.printStackTrace();
throw new HttpNodeClientException("HttpNodeClientException/IllegalStateException - createResponse():" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new HttpNodeClientException("HttpNodeClientException/IOException - createResponse():" + e.getMessage());
} catch (JSONException e) {
e.printStackTrace();
throw new HttpNodeClientException("HttpNodeClientException/JSONException - createResponse():" + e.getMessage());
} catch (ConverterException e){
e.printStackTrace();
throw new HttpNodeClientException("HttpNodeClientException/ConverterException - createResponse():" + e.getMessage());
}
And i get an JSONException. Did i design the JSON wrong?
Heres the exception:
08-14 16:14:18.522: I/LoginActivity(418): HttpNodeClientException/JSONException - createResponse
():Value {"id":"11111111","dateToday":"14082012","dateYesterday":"13082012","wbsArrayToday":
[{"wbs":"13232323"},{"wbs":"13232324"},{"wbs":"13232325"}],"wbsArrayYesterday":
[{"wbs":"13232333"},{"wbs":"13232334"},{"wbs":"13232335"}]} of type java.lang.String cannot be
converted to JSONObject

Use the JSONTokener class instead. It parses a string and return a JSON object.

the only line you need to fix is this one:
jsonObj = new JSONObject(result);
into this one:
jsonObj = new JSONObject(new JSONTokener(result));

Related

How to get JSONObject without JSONArray

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();
}

How to access volley response like this

How to access volley response {"data":"success"} like this.
i am already try this
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
You're trying to access a JSONArray from a JSONObject while it's just a string. So just replace getJSONArray with getString and try this
String data = new JSONObject(response).getString("data");
Or in your code
try {
JSONObject j = new JSONObject(response);
result = j.getString("data");
}
catch (JSONException e) {
e.printStackTrace();
}
Access Like This
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getString("data");
} catch (JSONException e) {
e.printStackTrace();
}
You can check this, before retrieving check if that tag (i.e. "data" for your case) is exists on that json object.
JSONObject j = null;
try {
j = new JSONObject(response);
if(j.has("data") {
result = j.getString("data");
}
} catch (JSONException e) {
e.printStackTrace();
}
As the value of data is string and to get string value you have to use JSONObject.getString("data")
Use:
result = j.getString("data");
Instead of:
result = j.getJSONArray("data");

How to serially get JSONObject from a txt file

I kept some JSON data in a txt file inside assests folder. Then i am reading the txt file and kept the result in a string. Now i am trying to convert the string to JSONObject and get some data from each key. Below is the code.
========method for reading from a file:
private String readMyJsonFile()
{
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("myFile.txt"), "UTF-8"));
mLine = reader.readLine();
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
return mLine;
}
======= And inside onCreate():
String JsonStr = readMyJsonFile();
try {
JSONObject jsonObj = new JSONObject(JsonStr);
JSONObject questionMark = JsonObj.getJSONObject("structure_details");
Iterator keys = questionMark.keys();
while(keys.hasNext())
{
String currentDynamicKey = (String)keys.next();
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
}
}
catch (JSONException e) {e.printStackTrace(); }
================================================
and the JSON data is:
{"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
}
==========================================================
I am getting result but the problem is that i am not getting the JSONObject serially in JSONObject jsonObj = new JSONObject(JsonStr); . The sequence is not the same as the JsonStr.
How to solve it?
Take the iterator keys in a ArrayList of string. Then loop through each arraylist object and get the JsonObjects. Following is the code that might help:
String JsonStr = readMyJsonFile(); //readMyJsonFile() is the same method you created
ArrayList<String> sortedKey = new ArrayList<String>();
try {
JSONObject jsonObj = new JSONObject(JsonStr);
JSONObject questionMark = jsonObj.getJSONObject("structure_details");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
sortedKey.add(currentDynamicKey);
}
Collections.sort(sortedKey);
for(String str:sortedKey )
{ JSONObject currentDynamicValue = questionMark.getJSONObject(str);
}
}
catch (Exception e) {
e.printStackTrace();
}
It is not JSON:
"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
It is JSON:
{"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}}
and it JSON:
{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}

Parsing Specific JSON data from website and Displaying in TextView

I am looking to pull data from my websites JSON url and display only one object in the textview. I was able to parse the entire JSON array, but not the specific object.
Here's the JSON on the site:
{"id":3,"day":" an A","created_at":"2013-11-06T12:30:59.023Z","updated_at":"2013-11-06T12:30:59.023Z"}
As you can see, it's pretty simple, but basically all I want to pull is the
"day":" an A"
and display it in my textview as "an A". Until now, I've only been able to pull the entire array.
A reference to this or any solution would be greatly appreciated!
Thanks in advance!
MainActivity Class:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parseDay);
TextView textView1 = null;
try {
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
JSONObject json=new JSONObject("day");
try {
String day =json.getString("day");
textView1.setText(day);
} catch (JSONException e) {
e.printStackTrace();
}
}
//catch (JSONException e) {
// e.printStackTrace();
//}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and My GetMethod:
public class GetMethod {
public String getInternetData() throws Exception {
BufferedReader in = null;
String data = null;
try {
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.xelatechnologies.com/hfdays/show.json");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}
finally {
if (in !=null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
I'm extremely new to JSON parsing so I'm sure it is not right at all. But it's worth a try!
The JSON you posted is a JSONObject. In java you can put that object into an JSONObject like this (You can use any serialize/deserializer you would like, many exist, for this example try org.json):
String json = "{\"id\":3,\"day\":\" an A\",\"created_at\":\"2013-11-06T12:30:59.023Z\",\"updated_at\":\"2013-11-06T12:30:59.023Z\"}";
JSONObject jsonObject = new JSONObject(json);
Now you have created a json object. Next you want to set the text on the text view. The key to get your value in this case is "day". So now all you have to do is use the provided getString(String value) method on the json object.
final String DAY = "day";
String dayValue= "";
try {
value = jsonObject.getString(DAY);
} catch (JSONException e) {
e.printStackTrace();
}
TextView textView = findViewById(R.id.text_view);
textView.setText(dayValue);
{"id":3,"day":" an A","created_at":"2013-11-06T12:30:59.023Z","updated_at":"2013-11-06T12:30:59.023Z"}
As its starts from '{' so it is an Object not Array
JSONObject json=new JSONObject("YOUR_JSON_STRING");
try {
String days=json.getString("day");
textview.setText(days);
} catch (JSONException e) {
e.printStackTrace();
}
Edited:
TextView textView1;
String response;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parseDay);
textView1 = (TextView)findViewById(R.id.your_textview_id);//First Initialise TextView
GetMethod method=new GetMethod();
response=method. getInternetData();// Then get the Json response
try{
JSONObject json=new JSONObject(response);
try {
String day =json.getString("day");
textView1.setText(day);
} catch (JSONException e) {
e.printStackTrace();
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And dont forget to add Internet Permission in Manifest file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Try like this.

Doctype returned from Server instead of String?

I'm using BitNami to test my django project. I'm creating a connection from android, passing to it a url to fetch some data from the database. The data is in this form:
{"apps": ["False", "Hello from notepade++", "My App", "Test"]}
here's how I'm fetching and receiving the data in android
public static ArrayList<String> getApps(){
HttpClient httpclient = new DefaultHttpClient();
HttpResponse responseCategories;
int categoriesStatusCode =0;
String responseCategoriesString = "";
ArrayList<String> out = new ArrayList<String>();
HttpGet httpgetCategories = new HttpGet("http://safwany/sampleproject/applications/fetch_apps");
try {
responseCategories = httpclient.execute(httpgetCategories);
categoriesStatusCode = responseCategories.getStatusLine().getStatusCode();
try {
responseCategoriesString = EntityUtils.toString(responseCategories.getEntity());
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
if(categoriesStatusCode==200){
JSONObject object;
try {
System.out.println(responseCategoriesString);
object = new JSONObject(responseCategoriesString);
JSONArray Jarray = object.getJSONArray("apps");
for(int i = 0; i < Jarray.length(); i++)
{
String s = (String) Jarray.get(i);
out.add(s);
//categoriesMap.put(s, 0);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return out;
}
When I try to print responseCategoriesString, I get the following:
04-01 22:55:56.335: I/System.out(9325): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="refresh" content="0;url=http://search.tedata.net/main?InterceptSource=0&ClientLocation=eg&ParticipantID=esrkzqp9pwh62lmydaf4wsy3i92taus2&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fsafwany%2Fsampleproject%2Fapplications%2Ffetch_apps&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0"/><script type="text/javascript">url="http://search.tedata.net/main?InterceptSource=0&ClientLocation=eg&ParticipantID=esrkzqp9pwh62lmydaf4wsy3i92taus2&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fsafwany%2Fsampleproject%2Fapplications%2Ffetch_apps&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0";if(top.location!=location){var w=window,d=document,e=d.documentElement,b=d.body,x=w.innerWidth||e.clientWidth||b.clientWidth,y=w.innerHeight||e.clientHeight||b.clientHeight;url+="&w="+x+"&h="+y;}window.location.replace(url);</script></head><body></body></html>
04-01 22:55:56.335: W/System.err(9325): org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
When I look at the response data you get I think you have trouble with some firewall or similar:
http://search.tedata.net/main?InterceptSource=0&ClientLocation=eg&ParticipantID=esrkzqp9pwh62lmydaf4wsy3i92taus2&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fsafwany%2Fsampleproject%2Fapplications%2Ffetch_apps&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0
Contains your requested url:
FailedURI=http%3A%2F%2Fsafwany%2Fsampleproject%2Fapplications%2Ffetch_apps
But FailedURI sounds like a company firefall/gateway with filter... you should check if your emulator/device can really access the safwany "domain". Maybe you should try an IP instead of safwany?

Categories

Resources