I have an android application which get jSON data through HttpGet. But I am facing some problem when I show the data in the text view. The second name in the JSON data shows like my attached photo below. But when I show the jSON data in browser it shows wrong like my photo. Sorry for my poor English.
Here is my activity:
HttpClient client = new DefaultHttpClient();
String url = "http://54.228.199.162/api/campaigns";
try {
String res;
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> reshan = new BasicResponseHandler();
res = client.execute(httpget, reshan);
Log.d("um1", res);
JSONArray jsonArray = new JSONArray(res);
//campaign.setText(res);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString(TAG_ID);
byte[] b = id.getBytes("utf-8");
String utfid = new String(b);
String name = jsonObject.getString(TAG_NAME);
byte[] s = name.getBytes("utf-8");
String utfname = new String(s);
Log.d("IDDDDDDD", id);
Log.d("Nameeeeeee", name);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, utfid);
map.put(TAG_NAME, utfname);
//Object contactList;
contactList.add(map);
}
HttpResponse httpresponse = client.execute(httpget);
int responsecode = httpresponse.getStatusLine().getStatusCode();
Log.d("responsenummmm", "um11111"+responsecode);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
};
Here is the jSON data file:
[{"_id":"520ba75acf17c8cc796b584b","name":"Oulu Liikkujan viikko 16-22.9.2013"},
{"_id":"52161d80ecaf181dc5982624","name":"Ylöjärvi Liikkujan viikko 16-22.9.2013"},
{"_id":"52262fa6d3ee051600d84c68","name":"Lapin yliopiston hyvinvointiviikko 16-22.9.2013"},
{"_id":"5293bbffbf2f15044800011d","name":"testi"}, {"_id":"52a318bbac059a0002000b4f","name":"Standing wave to Oulu"}]
Here is the problem in Text view:
The name of the second one in the text view(photo) should be look like:Ylöjärvi Liikkujan viikko 16-22.9.2013
Please help me.
write like this Html.fromHtml(YOUR STRING)
Try to decode your your value as below :
String decodedString = URLDecoder.decode(jsonObject.getString(TAG_ID), "UTF-8");
use this to display the name..
Html.fromHtml("<font color='#ffff0000'>enter...label</font>")
Related
Well,it is simple yet I am finding confused to extract the info.Could you give a look here:
formatted JSON Data
[
{
"catalogName":"a",
"categoryName":"aa",
"subCategoryName":"aaa",
"price":888.0,
},
{
"catalogName":"b",
"categoryName":"bb",
"subCategoryName":"bbb",
"productName":"hjb",
"price":9.0,
}
]
I would be printing this in my android app.Thanks
Here is how I do in my code:
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
// Check StatusLine result ....
// Convert response to a JSon Array:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
httpResponse.getEntity().writeTo(baos);
baos.close();
JSONArray jsonArray = new JSONArray(baos.toString())
for(int i = 0; i < jsonArray.length(); ++i)
{
// Extract values from JSON row:
JSONObject jsonObject = jsonArray.getJSONObject(i);
String catalogName = jsonObject.has("catalogName") ? jsonObject.getString("catalogName") : "";
String categoryName = jsonObject.has("categoryName") ? jsonObject.getString("categoryName") : "";
String subCategoryName = jsonObject.has("subCategoryName") ? jsonObject.getString("subCategoryName") : "";
String productName = jsonObject.has("productName") ? jsonObject.getString("productName") : "";
double price = jsonObject.has("price") ? jsonObject.getString("price") : 0.;
// Do stuff with data:
...
}
Please note that if a row misses a value (like productName) you must handle it. In the example I assign a default value but maybe it's not the best choice.
JSONArray jsonArray=new JSONArray("YOUR_JSON_ARRAY_NAME"); //Must be case sensitive
for(int i=0;i<jsonArray.length();i++){
JSONObject current_job= jsonArray.getJSONObject(i);
String catalogName= current_job.getString("catalogName");
//same for other fields. KEY must be case sensitive
...
...
}
This is a JSONArray :-) Parse it with this:
String json = /** your JSON **/
JSONArray array = new JSONArray(json);
And now you can take the data out of the object with getJSONObject(int index) :-)
I suggest using a JSON parsing library, such as Gson. It is fast and very simple to use.
https://github.com/google/gson
If you have a following class:
class Catalog{
private String catalogName;
private String categoryName;
private String subCategoryName;
private String productName;
private double price;
/** Getter, setters, optional: toString, constructor... **/
}
To parse it simply call:
Type listType = new TypeToken<List<Catalog>>() {}.getType();
List<Catalog> yourList = new Gson().fromJson(YOUR_JSON_STRING, listType);
Instead of this "confusing" code for listType you can use also Class (see documentation), but this is not possible in your case, as provided JSON format is a direct list of elements, it is not wrapped. For using a class you would have to wrap this JSON with another element.
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
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!
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.
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);
}