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.
Related
I am learning how to parse a response from a restful web service It is supposed to retreive a JSON string so I can parse it, I am using the apache libs in android. Following some questions here in StackOverflow I do the following:
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
ResponseHandler<String> handler = new BasicResponseHandler();
try{
result = httpClient.execute(request, handler); ...
with that I can retreive the result of the WS as this:
"[{\"CodigoRTA\":\"0\",\"MensajeRTA\":\"\",\"Respuesta\":\"[{\\"codigo\\":\\"05\\",\\"nombre\\":\\"ANTIOQUIA\\"},{\\"codigo\\":\\"76\\",\\"nombre\\":\\"VALLE DEL CAUCA\\"}]\"}]"
the thing is that I am trying to parse it with JSONObject and JSONArray without success; When I try to use the JSONObject the errorhandler says that it cannot convert the string into JSONObject, so I look up for an answer or a similar problem and found that if the result starts with [] square brackets represents starting of an JSONArray node and curly bracket {} represents JSONObject, so I try to use this code:
//JSONObject jsonObject = new JSONObject(result);
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
codeDepartment[i] = json_data.getInt("codigo");
NameDepartment[i] = json_data.getString("nombre");
}
without success either, it now says that "it cannot convert String into JSONArray. So any idea of what can I use? any help would be really appreciated.
Well, it seems that the server response is similar to Json response, the thing is all of the \ that it contains. One thing you could do is to replace or remove 1 of the \ backslash and then try to asign the new value to the JSONArray. Something like this:
result = httpClient.execute(request, handler);
result = result.replace("here the info you want to replace", "here with new values to replace with ");
JSONArray jArray = new JSONArray(result);
hope it help you.
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.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://gateway.ceylonlinux.com/hayleys2/services/getUserStokDetail?token=40da9b9ed74f672c3871d76a2c87857b×tamp=0");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpPost, responseHandler);
JSONObject posts = new JSONObject(responseBody);
JSONArray jArray = posts.getJSONArray("timestamp");
Log.i("Tag", jArray.toString());
I tried above code to retrieve data from server but when i try that i get following error
12-06 11:12:27.539: W/System.err(4870): org.json.JSONException: Value 1386308549000 at timestamp of type java.lang.Long cannot be converted to JSONArray
timestamp is value instead of JSONArray.stock is JSONArray. get both value as:
JSONArray jArray = posts.getJSONArray("stock"); /// get stock JSONArray
Log.i("Tag", jArray.toString());
long timestamp=posts.getLong("timestamp"); /// get timestamp
Replace this line
JSONArray jArray = posts.getJSONArray("timestamp");
With this one :
long mTimeStamp = posts.getLong("timestamp");
Because in your JSON String timestamp is an long value not an array
In your JSON String stock is an array so you can get stock by using this
JSONArray jArray = posts.getJSONArray("stock");
check your Json string whether it has jsonArray named timestamp or it have only a long variable named timestamp. you can check this link for json structure also.
I would like to pass JSON object as request to web service like i mentioned below.
Result:{
"email":"xxxxxxx",
"password":"xxxxxx",
"Marks":[
{
"mark1":"50",
"mark2":"70"
}
],
"firstname":"xxxx",
"lastname":"xxxxx"
}
My code:
...
HttpPost httppost = new HttpPost("My Url");
httppost.setEntity(new StringEntity(**message**.toString(), "UTF-8"));
Here message should have json object in above format.How could i format JSON object?
Thanks.
If you arer having trouble in implementing above json object at android side then you can construct it like below,
JSONObject message = new JSONObject();
JSONObject mParams = new JSONObject();
mParams.put("email", "xxxx");
mParams.put("password", "xxx");
JSONArray markArray = new JSONArray();
JSONObject markObj = new JSONObject();
markObj.put("mark1", "50");
markObj.put("mark2", "70");
markArray.put(markObj);
mParams.put("Marks", markArray);
mParams.put("FirstName", "xxxx");
mParams.put("lastname", "xxxx");
message.put("Result",mParams);
Now in your code
HttpPost httppost = new HttpPost("My Url");
httppost.setEntity(new StringEntity(**message**.toString(), "UTF-8"));
You can just send it like a String:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", message.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
and
$data = json_decode($json);
First of all, the JSON which you have mentioned above is INVALID.
Now,
Here message should have json object in above format.How could i
format JSON object?
=> There are 2 ways to do that:
1) Create a request structure by using JSONObject or JSONArray classes, something like:
JSONObject objRequest = new JSONObject();
objRequest.putString("email","xxxx");
objRequest.putString("password","xxxx");
while setting entity inside HttpPost object, convert it into the String value.
2) Bad way, simple generate a string value with escape sequences, something like:
String strRequest = "{\"email\":\"xxxxxxx\",\"password\":\"xxxxxx\"}";
This may help you..Use GSON library. GSON is a Google library to parse JSON resources. With regards to the Marshalling, it basically means a way to translate data structures (like objects in an OOP language) to JSON... for instance:
// Java object
class Book {
private String title;
private String isbn;
private Set<author> authors;
}
#Entity
class Author {
private String firstName;
private String lastName;
}
To...
{title: "Vocation Createurs",
isbn: "2829302680",
authors: [{firstName: "Barbara", lastName: "Polla"},
{firstName: "Pascal", lastName: "Perez"}]}
You can also use existing libraries like android-json-rpc
I have a JSONObject with 2 JSONArrays with JSONObjects. I'm wondering how do I access the JSONObjects in the JSONArray located in the JSONObject?(JSON inception!).
Clarify(even I get confused of writing it this)
I first get an JSONObject
This object contains 2 JSONArrays
These 2 arrays have X and Y amounts of JSONObjects.
How I reach the "Deepest" JSONObjects? How do I "unfold" the first JSONObject to get the first 2 JSONArrays?
Any hints or tricks to share?
Yuo could use something like this new JSONObject(json).getJSONArray(arrayname1).getJSONObject(positionx).
Here json is the JSON response string. arrayname1 is the name of your first array. and poitionx is any position fromX JSONObjects.
Similarly you could use new JSONObject(json).getJSONArray(arrayname2).getJSONObject(positiony) for the other one.
Any hints or tricks to share?
Yes, use a JSON library like GSON from Google.
Here is a reference on using it. http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/
Good luck!
Here is the example.
Suppose We have an JSONObject "Space" having two arrays: one and two.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("url");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
JSONObject json=new JSONObject(result);
JSONObject resp= (JSONObject) json.get("response");
JSONObject Space=resp.getJSONObject("Space");
JSONArray One=Space.getJSONArray("one");
int Length=One.length();
for(int i=0;i<length;i++)
{
JSONObject item = (JSONObject) items.get(j);
String x=item.getString("x);
String y=item.getString("y");
System.out.println("x = "+x+" , y = "+y);
}
And in the same manner you can work with second array.