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.
Related
after running the url i am getting data in the following form
[
{
"user_name": "riz",
"gems_available": "10",
"free_gems": "110"
},
{
"match_name": "ausvsind",
"Match_start_time": "2016-03-27 19:00:56",
"season_name": "Mid-Season"
}
]
now i want to get user_name and all the data but unable to do..i am getting this data in the result after running my app but unable to fetch.below i have my java code.please help me where i am wrong.
JSONObject jsonObj = new JSONObject();
jsonObj.put("user_id", "abc#hotmail.com");
jsonArray = new JSONArray();
jsonArray.put(jsonObj);
final HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(USER_URL);
String str = jsonArray.toString().replace("[", "");
String str1 = str.replace("]", "");
httppost.setEntity(new StringEntity(str1.toString()));
resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
result = EntityUtils.toString(ent);
jsonArray1.put(result);
jsobj = new JSONObject(result);
us1 = jsobj.getString(TAG_USER_NAME);
us2 = jsobj.getString(TAG_GEMS_AVAILABLE);
us3 = jsobj.getString(TAG_GEMS_FREE);
Have a look at Retrofit : it helps you parse JSON into a java POJO automagically and will help you avoid non-differential boilerplate
https://github.com/square/retrofit
When I have to get data from a Json, I always you serialization.
Have a Look at GSON. With it, you have to create model Objects that match the json architecture. After it, you can access all your json attributes easily.
There is another, better way to do this.
Use modern libraries for API calls like Retrofit 2.0 with GSON.
Add Retrofit 2.0 to your project
Read: https://github.com/square/retrofit
Create POJO Object from your JSON
http://www.jsonschema2pojo.org/
select Source type > JSON
select Annotation style > GSON
Create API service interface
Step by step: http://square.github.io/retrofit/
Why are you removing the "[" and "]" characters? Those are part of the JSONArray? If you did not want them there, use a JSONObject instead.
I did not test this, so it will have some issues. Conceptually this should work for you:
JSONObject jsonObj = new JSONObject();
jsonObj.put("user_id", "abc#hotmail.com");
final HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(USER_URL);
httppost.setEntity(new StringEntity(jsonObj.toString()));
resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
result = EntityUtils.toString(ent);
JSONArray jsonArr = new JSONArray(result);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jobj = jsonArr.getJSONObject(i);
if (jobj.has("user_name"))
{
us1 = jobj.getString("user_name");
}
if (jobj.has("gems_available"))
{
us2 = jobj.getString("gems_available");
}
if (jobj.has("free_gems"))
{
us3 = jobj.getString("free_gems");
}
}
This question already has answers here:
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
Closed 9 years ago.
I have following objects in JSON file. I have to parse it and store it in a file. What will be the android code for doing this?
{
"result":"ok",
"numbers":
[
{
"First":"first",
"Second":"second",
"Third":"third",
"Fourth":"fourth",
"Fifth":"fifth"
}
]
}
Any one find me getting out of this? I would really appreciate your work.
{ -> json object
"result":"ok",
"numbers":[-> json array
{
Do like this
JSONObject jobject=new JSONObject(jsonString);
JSONArray jarray=Jobject.getJSONArray("numbers");
String result=jobject.getJSONObject("result");
for(int i=0;jarray.length();i++){
String first= jarray.getJSONObject(i).getString("First");
String Second= jarray.getJSONObject(i).getString("Second");
}
{ // json object node
"result":"ok",
"numbers":[// json array numbers
{
"First":"first",
To parse
JSONObject jb = new JSONObject("your json");
String result = (JSONArray)jb.getString("result");
JSONArray jr = (JSONArray)jb.getJSONArray("numbers");
JSONObject jb1= (JSONObject) jr.getJSONObject(0);
String first = jb1.getString("First");
// similarly for second third and fourth
Once you parse you can write the result to a file.
Edit:
Note: Network operation must be done in a background thread. Use Asynctask
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("your json url ");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
}catch(Exception e)
{
e.printStackTrace();
}
Now use _response JSONObject jb = new JSONObject("_response);. Rest all is the same
Try Using the following
import org.json.JSONArray;
import org.json.JSONObject;
JSONObject json = null;
JSONArray jsonArray = null;
String data = null;
json = new JSONObject(response);
data = json.getString("numbers");
jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
String str =jsonArray.getJSONObject(i).toString();
}
always remember { means object and [ means array so you can proceed with following code in the give
JSONObject firstjobject=new JSONObject(jsonString);
JSONArray firstjarray=firstjobject.getJSONArray("numbers");
String result=firstjobject.getJSONObject("result");
for(int i=0;firstjarray.length();i++){
String first= firstjarray.getJSONObject(i).getString("First");
String Second= firstjarray.getJSONObject(i).getString("Second");
}
here numbers is an array and First,Second etc are the keys for relative data values
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 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.
I am making an app in which i am getting a string as response from server side. that response is encoded in json. Now my problem is How to do json parsing of the encoded response from server side to decode it..
I am geting the following response from server
["ekjyot#emobx.com","prince6179#gmail.com","facebook_514728069"]
It is in the form of an array.I want to decde it and display as textviws in my another activity.
I am using the following code:
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.ondamove.it/English/mob/profile_friends.php?email="+Login.eMailId+"";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null)
{
String s = EntityUtils.toString(resEntityGet);
System.out.println(s);
JSONArray ids = new JSONArray(s);
for(int i=0; i< ids.length(); i++){
System.out.println(ids[]); //print each of the string in json array.
}
but it is giving me the error :
The type of the expression must be an array type but it resolved to JSONArray
how to resolve this issue.
can anyone help me over this?
thanks
You can use JSONTokener to parse JSON documents for example:
String json = "{"
+ " \"query\": \"Pizza\", "
+ " \"locations\": [ 94043, 90210 ] "
+ "}";
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
String query = object.getString("query");
JSONArray locations = object.getJSONArray("locations");
get your response as string
String jsonResponseString = Sever.getResponse();
JSONArray ids = new JSONArray(jsonResponseString);
for(int i=0; i< ids.length(); i++){
Log.i(TAG, ids[i]); //print each of the string in json array.
}
GSON if you just want to keep it simple. Jackson streaming if you need raw speed.
Or you could always use the built in JSON tools -- but I'd recommend one of these other two.