I am trying to parse JSON from web service. But i get "String could not be converted to Json Object" error.
My json: {"encoding":"UTF-8","yorumlar":[["dogukan","deneme yorumu"],["Burak","yorum"]]}
I get this string like below;
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(url);
HttpResponse response = null;
try
{
response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
.
.
.
When i got this string from web service like above, i get this error but when i do that:
JsonObject object = new JsonObject("{\"encoding\":\"UTF-8\",\"yorumlar\":[[\"dogukan\",\"deneme yorumu\"],[\"Burak\",\"yorum\"]]}")
i don't get this error. So, the strings are the same and json format is ok. What is the problem?
I solved the problem, the json string starts with these characters "". But these characters does not appear in debug mode. I created a java project. And i got the json string from server. I saw these characters in debug mode. Java project gave me more details about the converting error.
if you try to get the values of these in debug mode:
jsonString.toCharArray()[0] and jsonString.toCharArray()[1]
you will see the values as "", not "{". It's not space but does not appear. and "{" character located in 2. index.
We have solved the problem on server side. I guess that was an page encoding problem.
Related
In my code, I am trying to access some json return from server. But I can't convert json return from server to JsonObject. Here is my code,
result = post.getHttpData(Constants.UrlDepartureCity);
catchLog(result);
JSONObject obj=new JSONObject(result);
I use my custom catchLog to print json return in log.
09-23 14:53:59.940: I/DepartureCityAsync(23313):
{"status":"1","departure_city":[
{"entity_id":"1","field_depature_city_tid":"1","entity_type":"node"},
{"entity_id":"8","field_depature_city_tid":"1","entity_type":"node"},
{"entity_id":"12","field_depature_city_tid":"1","entity_type":"node"},
{"entity_id":"5","field_depature_city_tid":"2","entity_type":"node"},
{"entity_id":"9","field_depature_city_tid":"2","entity_type":"node"},
{"entity_id":"17","field_depature_city_tid":"2","entity_type":"node"},
{"entity_id":"6","field_depature_city_tid":"3","entity_type":"node"},
{"entity_id":"7","field_depature_city_tid":"5","entity_type":"node"}]}
And I copy the result and validate that json return in http://jsonlint.com/. There is no error, syntax also correct. But When I try to convert it to JsonObject I got this error.
09-23 14:53:59.940: W/System.err(23313): org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
How can I solve this problem? Please.
Thanks
I think there may be some blank characters in your return. Change it to
JSONObject obj=new JSONObject(result.trim());
I think your json format is wrong or has some little mistake. From this link, you can find a solution.
final TextView res=(TextView)findViewById(R.id.res);
try
{
HttpClient client=new DefaultHttpClient();
HttpPost request=new HttpPost("http://192.168.0.30/test.js");
HttpResponse response=client.execute(request);
HttpEntity entity=response.getEntity();
res.setText(EntityUtils.toString(entity));
}
catch(Exception e)
{
res.setText(e.toString());
}
here is my code sample it works for me...for the same json as you provided.
can you show me your code how you get the response.i didn't get the method getHttpData() you've used.
I wrote a web service in asp.net and called it in my android application using a JSON webservice. This is my code to call the web service from android
httpPost request = new HttpPost(url);
request.setHeader("Content-Type","application/json");
request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);
String jsonResponse = EntityUtils.toString(response.getEntity());
JSONObject jobj=new JSONObject(jsonResponse);
JSONArray jsonArray=jobj.getJSONArray("d");
result=(String) jobj.getString("d")
I need to get each value from the result. How is it possible?
My web service result is:
{"d":"{\"Password\":33,\"Userid\":\"343\",\"Username\":fgfg}"}
Just remove below line
JSONArray jsonArray=jobj.getJSONArray("d");
because you don't ve any JSONArray in your response then d is the only object then remaining all values are in string because all in double cotes("")...
First of all,form your json like below:
{"d":{\"Password\":33,\"Userid\":\"343\",\"Username\":fgfg}}
So,that you can get,
JSONObject jobj=new JSONObject(jsonResponse);
JSONObject jsonObj=jobj.getJSONObject("d");
now you can get the value for Username like:
String Username = jsonObj.getString("Username");
Similarly you can get the other values also..
Just do
resultPassword = jsonArray.getString("Password");
That should work. Obviously change "Password" for each ID of the data you want to get.
I'm a noob to android and I'm trying to parse a JSON from this link: "http://services.packetizer.com/spotprices/?f=json". However, when I send my request to parse it, i receive an error saying..." Error parsing data org.json.JSONException: Value xml of type java.lang.String cannot be converted to JSONObject". This is baffling to say the least because the link is obviously a JSON. Any help solving this is greatly appreciated.
My Code:
JSONObject json = JSONfunctions.getJSONfromURL("http://services.packetizer.com/spotprices/?f=json");
if(json==null){
//Do Nothing
}else{
String usdgold = json.getString("gold");
livespotgold = Double.parseDouble(usdgold);
storedspotgold=livespotgold;
Log.e("Spot Gold Packetizer", String.valueOf(livespotgold));
String usdsilver = json.getString("silver");
livespotsilver = Double.parseDouble(usdsilver);
storedspotsilver=livespotsilver;
Log.e("Spot Silver Packetizer", String.valueOf(livespotsilver));
haveSpot = true;
}
I assume you're using the JSONfunctions class from here or a modified version of it (as you're receiving a JSONObject and not a JSONArray).
Note that that code sends an HTTP POST. This endpoint is returning XML when you send it a POST. You need to change the code to send an HTTP GET:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
I am sending a JSON object to a HTTP Server by using the following code.
The main thing is that I have to send Boolean values also.
public void getServerData() throws JSONException, ClientProtocolException, IOException {
ArrayList<String> stringData = new ArrayList<String>();
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://consulting.for-the.biz/TicketMasterDev/TicketService.svc/SaveCustomer");
JSONObject json = new JSONObject();
json.put("AlertEmail",true);
json.put("APIKey","abc123456789");
json.put("Id",0);
json.put("Phone",number.getText().toString());
json.put("Name",name.getText().toString());
json.put("Email",email.getText().toString());
json.put("AlertPhone",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
String response = httpClient.execute(postMethod,resonseHandler);
Log.e("response :", response);
}
but its showing the exception in the line
String response = httpClient.execute(postMethod,resonseHandler);
as
org.apache.http.client.HttpResponseException: Bad Request
can any one help me.
The Bad Request is the server saying that it doesn't like something in your POST.
The only obvious problem that I can see is that you're not telling the server that you're sending it JSON, so you may need to set a Content-Type header to indicate that the body is application/json:
postMethod.setHeader( "Content-Type", "application/json" );
If that doesn't work, you may need to look at the server logs to see why it doesn't like your POST.
If you don't have direct access to the server logs, then you need to liaise with the owner of the server to try and debug things. It could be that the format of your JSON is slightly wrong, there's a required field missing, or some other such problem.
If you can't get access use to the owner of the server, the you could try using a packet sniffer, such as WireShark, to capture packets both from your app, and from a successful POST and compare the two to try and work out what is different. This can be a little bit like finding a needle in a haystack though, particularly for large bodies.
If you can't get an example of a successful POST, then you're pretty well stuffed, as you have no point of reference.
This may be non-technical, but
String response = httpClient.execute(postMethod,-->resonseHandler);
There is a spelling mistake in variable name here, use responseHandler(defined above)
I am getting some weird errors with my Android App. It appears that this code is double encoding the JSON string. What should be sent is ?{"email":"asdf#asdf.com","password":"asdf"}
or
?%7B%22email%22:%22.....
what the server is seeing is %257B%2522email%2522:%2522 ....
which means the server sees %7B%22email%22:%22 .....
This confuses the server.
Any ideas why this is happening?
Thank you for your help
//edited to define objects better
Code:
DefaultHttpClient c = new DefaultHttpClient();
if(cookies!=null)
c.setCookieStore(cookies);
JSONObject jso = new JSONObject():
if(loginNotLogout){
jso.put("email", "email#email.com");
jso.put("password", "PassW0RD");
}
URI u = null;
if(loginNotLogout)
u= new URI("HTTP","www.website.com","/UserService",jso.toString(),"");
else
u= new URI("HTTP","www.website.com","/UserService",jso.toString(),"");
HttpGet httpget = new HttpGet(u);
HttpResponse response = c.execute(httpget);
ret.jsonString = EntityUtils.toString(response.getEntity());
what is userData ?
are you getting values from any EditText?
will using getText().toString() with the text from EditText help?
As it turns out, dropping the "www." from the authority field in the URI constructor caused the address string to be encoded correctly.
I am no web expert, but if anyone can explain this I am all ears. or eyes in this case.
--
Andrew