How can i get data from server? - android

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

Related

How to parse a specific response of a RESTful WS using JSON

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.

Which Collection should I convert in JSON and parse again?

Sorry for the title, I explain.
I'm developing an Android app that use a WebService on Google App Engine.
In my WebService I've an ArrayList converted in JSON trough JAX-RS, and the final JSON is something like
{ "lessons" : [ { "name" : "blabla", "prof":"Tom" }, { "name" :
"blabla", "prof":"Tom" } ] }
Is this practical or is there a better way?
Then I fetch this JSON from the Android app and convert it in a JSONObject with a snipplet found online:
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(s);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new
InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONObject jsonObject = new JSONObject(json);
How can I get back to my ArrayList?
I've read tons of code and tried to use Gson...
This should be easy but I've lost an entire day yesterday..
private class Info {
public String name;
public String prof;
}
ArrayList<Info> arrayList = new ArrayList<Info>();
JSONArray array = jsonObject.optJSONArray("lessons");
int len = array.length();
for (int i = 0; i < len ; i++) {
JSONObject tmp = array.optJSONObject(i);
Info info = new Info();
info.name = tmp.optString("name");
info.prof = tmp.optString("prof");
arrayList.add(info)
}
check for mispelling error
Download my example from this post. A fully working source code showing how do you convert an object to a json object. Hope it help. How to save an array of simple objects in my android app?
If you want to go with the built in JSON-classes, you could do something like this:
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(s);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONObject jsonObject = new JSONObject(json);
if (jsonObject.has("lessons")) {
JSONArray jsonLessons = jsonObject.getJSONArray("lessons");
List<Lesson> lessons = new ArrayList<Lesson>();
for(int i = 0; i < jsonLessons.length(); i++) {
JSONObject jsonLesson = jsonLessons.get(i);
// Use optString instead of get on the next lines if you're not sure
// the fields are always there
String name = jsonLesson.getString("name");
String teacher = jsonLesson.getString("prof");
lessons.add(new Lesson(name, teacher));
}
}
Just be sure that your Json always arrives in a single line. Breaking a line would break this code, as you only read the line.
My choice would be Gson. In this case you would create a Lesson class and a Schedule class:
public class Lesson {
String name;
String prof;
}
public class Schedule {
List<Lesson> lessons;
}
Note that the field names corresponds to the json fields. Feel free make the fields private and add som getter methods if that feels better. :-)
Now you can parse out the Schedule object containing the lessons list with:
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(s);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
Reader in = new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8");
Gson gson = new Gson();
Schedule schedule = gson.fromJson(in, Schedule.class);
List<Lesson> lessons = schedule.lessons;
Hope this helps!

passing an array of string using json

JSONObject jsonObj = new JSONObject();
jsonObj.put("email", email);
jsonObj.put("password", password);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost("http://api.readfa.st/session");
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);`
Currently I am working in an android project where i need to pass an array user[email], user[password] to a web page using json...please if any one can help me width this asap..Thank you!
I'm not sure what you mean. But I guess you need something like this:
JSONArray jsonArray = new JSONArray(listOfUsers);
String jsonRepresentationForListOfUsers = jsonArray.toString();
You can look here for further documentation.
http://developer.android.com/reference/org/json/JSONArray.html

android:json parsing to decode

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.

How to use JSON for inserting records into SQL database

Let's say I store a list of names , for eg: "abc","bcd","gdf"... in an array of Strings. I have an Android app that displays each of those values along with a checkbox. I need to convert my String array into a JSON String so that I can store it in a remote database. Right now I am working on localhost with a database created using SQL Server. I need to insert the JSON string values in the database using a web service , preferably SOAP
How should I do this ? Is there any other better way to do so ?
Here is my Android code.
Thanks
In my case this works fine,
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", value1);
jsonObject.put("key2", value2);
JSONArray jArrayParam = new JSONArray();
jArrayParam.put(jsonObject);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("bulkdata",
jArrayParam.toString()));
Log.e("bulkdata", jArrayParam.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("yor remote database url");
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// get response entity
HttpEntity entity = response.getEntity();
Try it. Thnx.
Well, I just tried to show you how to write the String array to JSONObject and JSONArray.
String arr[] = {"1","parth","present","30-82011","Mumbai"};
try {
JSONObject obj=new JSONObject();
obj.put("rollno",new Integer(arr[0]));
obj.put("status",arr[1]);
obj.put("date",arr[2]);
obj.put("place",arr[3]);
System.out.print(obj.toString(1));
JSONArray list = new JSONArray();
list.put(arr[0]);
list.put(arr[1]);
list.put(arr[2]);
list.put(arr[3]);
System.out.print(list.toString(1));
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
var arr:String = com.adobe.serialization.json.JSON.encode(Obj);
var data_projects:Array = stmt.getResult().data;
var b_data:String = com.adobe.serialization.json.JSON.encode(data_projects);
var arr:String = com.adobe.serialization.json.JSON.encode(data_projects);
var arr1:Object = com.adobe.serialization.json.JSON.decode(b_data) as Array;
 for(var d:int=0;d<=data_projects.length-1;d++)
 
{
//Mapping properties of Proxy classes with actual fields
var bbb:Object = new Object;
data.MdId = arr1[d].MD_ID;
data.MdDevId=arr1[d].MD_DEVICE_ID;
data.MdRecId=arr1[d].MD_REC_ID;
data.MdPrjId= arr1[d].MD_PRJ_ID ;
data.MdMbcId = arr1[d].MD_MBC_ID;
data.MdMbcValue= arr1[d].MD_MBC_VALUE;
data.MdParentRecId= arr1[d].MD_MBC_ID;
//below is the create method on the WSDL
ws.Create(data);
}

Categories

Resources