I have a json response as shown below
[
{
"id": "1",
"name": "b day",
"date": "2015-12-08",
"start_time": "00:50:02",
"end_time": "05:00:00"
},
{
"id": "2",
"name": "game",
"date": "2015-11-18",
"start_time": "00:00:02",
"end_time": "09:10:00"
}
]
My android code to retrieve json is given below
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
You can get JSONArray like below.
JSONArray jsonArray = new JSONArray(responseString);
From array you can get JSONObject like below.
for(int i = 0 ; i< jsonArray.length() ; i++){
// This will get first JSONObject from JSONArray.
JSONObject jObject = jsonArray.getJSONObject(i);
// Get all key from array using JSONObject.
String id = jObject.getString("id");
String name = jObject.getString("name");
String date = jObject.getString("date");
String startTime = jObject.getString("start_time");
String endTime = jObject.getString("end_time");
}
Try this:
try
{
JSONObject issueObj = new JSONObject(JSONString);
Iterator iterator = issueObj.keys();
while (iterator.hasNext())
{
String key = (String) iterator.next();
JSONObject issue = issueObj.getJSONObject(key);
int pubKey = Integer.valueOf(issue.optString("id"));
mylist.add(pubKey);
JSONObject json = new JSONObject(JSONString);
JSONObject jArray = json.getJSONObject(String.valueOf(pubKey));
nameString = jArray.getString("name");
dateString = jArray.getString("date");
start_timeString = jArray.getString("start_time");
end_timeString = jArray.getString("end_time");
}
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Use this code
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
json = response.toString();
JSONArray jsonArray = new JSONArray(json);
ArrayList<String> al_ids=new ArrayList<String>();
Arraylist<String> al_name=new ArrayList<String>();
Arraylist<String> al_date=new ArrayList<String>();
Arraylist<String> al_start_time=new ArrayList<String>();
Arraylist<String> al_end_time=new ArrayList<String>();
for(int i = 0 ; i< jsonArray.length() ; i++){
// This will get first JSONObject from JSONArray.
JSONObject jObject = jsonArray.getJSONObject(i);
// Get all key from array using JSONObject.
String id = jObject.getString("id");
String name = jObject.getString("name");
String date = jObject.getString("date");
String startTime = jObject.getString("start_time");
String endTime = jObject.getString("end_time");
al_ids.add(id);
al_name.add(name);
al_date.add(date);
al_start_time.add(startTime);
al_end_time.add(endTime);
}
//here you can set text to Your TextView by getting position of arraylist
Related
The problem is that in first row data save normally but in second row or move on data redundant Like:
public void Save(){
String register;
JSONObject jsonObj;
JSONObject json;
JSONArray jsonTempArray = new JSONArray();
JSONObject jsonObject=new JSONObject();
JSONArray jsonArray=new JSONArray();
try{
JSONObject jsonObjs=new JSONObject();
jsonObj=new JSONObject();
json=new JSONObject();
Integer.valueOf(mGeneralID);
str_UpdatedGeneralID= "6832";
String str_FMeasurementSamplesize = "";
if (txtFMeasurementSamplesize.getText().toString().equals("")){
str_FMeasurementSamplesize = "0";
}else {
str_FMeasurementSamplesize = txtFMeasurementSamplesize.getText().toString();
}
String Samplesize = txt_Sample_Size.getText().toString();
String Qtypersize = txt_Qty_per_Size.getText().toString();
String TotalnoofmeasPointsizeA = txtTotalnoOfmeasPointsizeA.getText().toString();
String TotalnoofmeasPointsizeAA = txtTotalnoOfmeasPointsizeAA.getText().toString();
String TotalnoofmeasPointsizeB = txtTotalnoOfmeasPointsizeB.getText().toString();
String TotalnoofmeasPointsizeBB = txtTotalnoOfmeasPointsizeBB.getText().toString();
String NomeasurementptoutoftolA = txtNomeasurementptoutoftolA.getText().toString();
String NomeasurementptoutoftolB = txtNomeasurementptoutoftolB.getText().toString();
String PASS = txt_pass.getText().toString();
String Fail = txt_fail.getText().toString();
String Pending = txt_pending.getText().toString();
String Remarks = txt_Remarks_F.getText().toString();
DateFormat df = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
String CreationDate = df.format(Calendar.getInstance().getTime());
int a =0;
for (int i=0; i < MeasurementArrayList.size(); i++){
String MeasurementSheetDetailID = MeasurementArrayList.get(i).getmeasurementSheetDetailID();
String MeasurementPointID = MeasurementArrayList.get(i).getmeasurementPointID();
String MeasurementPoints = MeasurementArrayList.get(i).getmeasurementPoints();
String SpecSizeA = MeasurementArrayList.get(i).getSpecSizeA();
String SpecSizeAOne = MeasurementArrayList.get(i).getSpecSizeAOne();
String SpecSizeATwo = MeasurementArrayList.get(i).getSpecSizeATwo();
String SpecSizeAThree = MeasurementArrayList.get(i).getSpecSizeAThree();
String SpecSizeAFour = MeasurementArrayList.get(i).getSpecSizeAFour();
String SpecSizeAFive = MeasurementArrayList.get(i).getSpecSizeAFive();
String SpecSizeB = MeasurementArrayList.get(i).getSpecSizeB();
String SpecSizeBOne = MeasurementArrayList.get(i).getSpecSizeBOne();
String SpecSizeBTwo = MeasurementArrayList.get(i).getSpecSizeBTwo();
String SpecSizeBThree = MeasurementArrayList.get(i).getSpecSizeBThree();
String SpecSizeBFour = MeasurementArrayList.get(i).getSpecSizeBFour();
String SpecSizeBFive = MeasurementArrayList.get(i).getSpecSizeBFive();
String Tolerance = MeasurementArrayList.get(i).gettolerance();
jsonObj.put("MeasurementSheetID", str_FMeasurementSamplesize);
jsonObj.put("GeneralID", str_UpdatedGeneralID);
jsonObj.put("Samplesize", Samplesize);
jsonObj.put("Measurement", str_sp_Measurement);
jsonObj.put("Qtypersize", Qtypersize);
jsonObj.put("Color", str_sp_Color);
jsonObj.put("SpecSizeA", str_sp_SpecSizeA);
jsonObj.put("SpecSizeB", str_sp_SpecSizeB);
jsonObj.put("TotalnoofmeasPointsizeA",TotalnoofmeasPointsizeA);
jsonObj.put("TotalnoofmeasPointsizeAA", TotalnoofmeasPointsizeAA);
jsonObj.put("TotalnoofmeasPointsizeB", TotalnoofmeasPointsizeB);
jsonObj.put("TotalnoofmeasPointsizeBB", TotalnoofmeasPointsizeBB);
jsonObj.put("NomeasurementptoutoftolA", NomeasurementptoutoftolA);
jsonObj.put("NomeasurementptoutoftolB", NomeasurementptoutoftolB);
jsonObj.put("PASS", PASS);
jsonObj.put("Fail", Fail);
jsonObj.put("Pending", Pending);
jsonObj.put("Remarks", Remarks);
jsonObj.put("CreationDate", CreationDate);
jsonObj.put("MeasurementSheetDetailID", MeasurementSheetDetailID);
jsonObj.put("MeasurementPointID", MeasurementPointID);
jsonObj.put("MeasurementPoints", MeasurementPoints);
jsonObj.put("SpecSizeA", SpecSizeA);
jsonObj.put("SpecSizeAOne", SpecSizeAOne);
jsonObj.put("SpecSizeATwo", SpecSizeATwo);
jsonObj.put("SpecSizeAThree", SpecSizeAThree);
jsonObj.put("SpecSizeAFour", SpecSizeAFour);
jsonObj.put("SpecSizeAFive", SpecSizeAFive);
jsonObj.put("SpecSizeB", SpecSizeB);
jsonObj.put("SpecSizeBOne", SpecSizeBOne);
jsonObj.put("SpecSizeBTwo", SpecSizeBTwo);
jsonObj.put("SpecSizeBThree", SpecSizeBThree);
jsonObj.put("SpecSizeBFour", SpecSizeBFour);
jsonObj.put("SpecSizeBFive", SpecSizeBFive);
jsonObj.put("Tolerance", Tolerance);
jsonTempArray.put(jsonObj);
}
jsonObject.put("jsondata",jsonTempArray);
register=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
return;
}
new save(register).execute();
}
Result: Both rows are same that`s the problem
Row 1
[{"MeasurementSheetID":"0","GeneralID":"6832","Samplesize":"10","Measurement":"INCH","Qtypersize":"5","Color":"Black","SpecSizeA":"6.5","SpecSizeB":"6.5","TotalnoofmeasPointsizeA":"30","TotalnoofmeasPointsizeAA":"125","TotalnoofmeasPointsizeB":"30","TotalnoofmeasPointsizeBB":"125","NomeasurementptoutoftolA":"0","NomeasurementptoutoftolB":"0","PASS":"d","Fail":"h","Pending":"k","Remarks":"g","CreationDate":"2018-11-305
05:04:28","MeasurementSheetDetailID":"0","MeasurementPointID":"2","MeasurementPoints":"BACK
POCKET POSITION POSITION OUTER
EDGE","SpecSizeAOne":"","SpecSizeATwo":"","SpecSizeAThree":"","SpecSizeAFour":"","SpecSizeAFive":"","SpecSizeBOne":"","SpecSizeBTwo":"","SpecSizeBThree":"","SpecSizeBFour":"","SpecSizeBFive":"","Tolerance":"+/-0.5"},
Row 2
{"MeasurementSheetID":"0","GeneralID":"6832","Samplesize":"10","Measurement":"INCH","Qtypersize":"5","Color":"Black","SpecSizeA":"6.5","SpecSizeB":"6.5","TotalnoofmeasPointsizeA":"30","TotalnoofmeasPointsizeAA":"125","TotalnoofmeasPointsizeB":"30","TotalnoofmeasPointsizeBB":"125","NomeasurementptoutoftolA":"0","NomeasurementptoutoftolB":"0","PASS":"d","Fail":"h","Pending":"k","Remarks":"g","CreationDate":"2018-11-305
05:04:28","MeasurementSheetDetailID":"0","MeasurementPointID":"2","MeasurementPoints":"BACK
POCKET POSITION POSITION OUTER
EDGE","SpecSizeAOne":"","SpecSizeATwo":"","SpecSizeAThree":"","SpecSizeAFour":"","SpecSizeAFive":"","SpecSizeBOne":"","SpecSizeBTwo":"","SpecSizeBThree":"","SpecSizeBFour":"","SpecSizeBFive":"","Tolerance":"+/-0.5"}]
You need to put this jsonObj=new JSONObject(); inside your loop.
So every time loop execute it will create new JSONObject and put it into JSONArray
JsonArray is composed by jsonObjects.
You need to empty jsonobject, populate it and put in jsonarray for every object in jsonArray.
jsonObj = new JSONObject();
Some documentation
how I can access data from a JSONArray? It is this and contains this information:
"deadlines": [
{
"start": 1439539200,
"end": 1439542800
},
{
"start": 1440144000,
"end": 1440147600
},
{
"start": 0,
"end": 0
}
]
I need to have in a String tag each item "start". Thanks
EDIT
My code is this:
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
for (int j=0; j < array.length(); j++)
{
try
{
JSONObject obj = array.getJSONObject(j);
String start = obj.getString("start");
String end = obj.getString("end");
Log.e("", "start = " + start);
}
catch (JSONException e)
{
Log.e("", "error = " + e.getMessage());
}
}
I get this error:
"error = No value for start"
Do this
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
JSONArray jArray = array.getJSONObject(0).getJSONArray("deadlines");
for (int i = 0; i < jArray.length(); i++) // assuming your array is jArray
{
try
{
JSONObject obj = jArray.getJSONObject(i);
String start= obj.getString("start"); // store in an ArrayList
String end = obj.getString("end"); //// store in an ArrayList
}
catch (JSONException e)
{
// Error
}
}
JSONArray mJsonArray=new JSONArray("Deadlines");
for(int i=0;i<mJsonArray.length();i++){
JSONObject mJsonObject=new JSONObject(mJsonArray.get(i).toString));
String start = mJsonObject.optString("start","");
String end = mJsonObject.optString("end","");
}
Try this:
StringBuilder sb = new StringBuilder();
JSONArray arr = new JSONArray("deadlines");
for(int i=0;i<arr.length;i++){
JSONObject obj = arr.getJSONObject(i);
sb.append(obj.get("start").toString());
sb.append(",");
}
String strStartTag = sb;
JSONArray ja = new JSONArray(yourjsondata));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo_feed = new JSONObject(ja.get(i).toString());
String start = jo_feed.getString("start");
}
Here is my JSON:
{
"id": "11111",
"title": "title?",
"url": "www.example.com",
"fulltext": {
"page1": "<p>balblabba</p>",
"page2": "<p>avavaava</p>"
},
"related_articles": [
{
"id": "123",
"title": "title",
"image_name": "www.example.com/image1.png"
}
]
}
I need to put everything in Strings. I'm using this code:
String data = JSON TEXT!!!;
JSONObject jRealObject = new JSONObject(data);
String title = jRealObject.getString("title").toString();
String url = jRealObject.getString("url").toString();
String fulltext = jRealObject.getString("fulltext").toString();
String page1 = ????
String page2 = ????
jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
String relatedId = jRealObject.getString("id").toString();
String relatedTitle = jRealObject.getString("title").toString();
String relatedImage = jRealObject.getString("image_name").toString();
}
I'm getting everything, But I want to split "fultext" into two variables. but I don't know how can I get "page1" and "page2".
Here in your response "fulltext" is another Jsonobject use below code to get other data.
JSONObject fulltextobj = jRealObject.getJSONObject("fulltext");
String page1 = fulltextobj.getString("page1");
String page2 = fulltextobj.getString("page2");
JSONObject obj = jRealObject.getJSONObject("fulltext");
String var1 = obj.getString("page1");
String var2 = obj.getString("page2");
EDIT: You have a JSONObject nested into another JSONObject. fulltext is not a String, is a JSONObject indeed, so you have to get a JSONObject from parent
Try this way,hope this will help you to solve your problem.
try{
JSONObject jsonObject = new JSONObject("{\"id\":\"11111\",\"title\":\"title?\",\"url\":\"www.example.com\",\"fulltext\":{\"page1\":\"<p>balblabba</p>\",\"page2\":\"<p>avavaava</p>\"},\"related_articles\":[{\"id\":\"123\",\"title\":\"title\",\"image_name\":\"www.example.com/image1.png\"}]}");
HashMap<String,Object> responseMap = new HashMap<String, Object>();
ArrayList<HashMap<String,String>> articleList = new ArrayList<HashMap<String, String>>();
responseMap.put("id",jsonObject.getString("id"));
responseMap.put("title",jsonObject.getString("title"));
responseMap.put("url",jsonObject.getString("url"));
JSONObject fullTextJsonObject = jsonObject.getJSONObject("fulltext");
responseMap.put("page1",fullTextJsonObject.getString("page1"));
responseMap.put("page2",fullTextJsonObject.getString("page2"));
JSONArray relatedArticleJsonArray = jsonObject.getJSONArray("related_articles");
for(int i=0;i<relatedArticleJsonArray.length();i++){
HashMap<String,String> articleRow = new HashMap<String, String>();
articleRow.put("id", relatedArticleJsonArray.getJSONObject(i).getString("id"));
articleRow.put("title", relatedArticleJsonArray.getJSONObject(i).getString("title"));
articleRow.put("image_name", relatedArticleJsonArray.getJSONObject(i).getString("image_name"));
articleList.add(articleRow);
}
responseMap.put("related_articles",articleList);
System.out.print("id : "+responseMap.get("id").toString());
System.out.print("title : "+responseMap.get("title").toString());
System.out.print("url : "+responseMap.get("url").toString());
System.out.print("page1 : "+responseMap.get("page1").toString());
System.out.print("page2 : "+responseMap.get("page2").toString());
ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>)responseMap.get("related_articles");
for (HashMap<String,String> row : list){
System.out.print("id : "+row.get("id"));
System.out.print("title : "+row.get("title"));
System.out.print("image_name : "+row.get("image_name"));
}
}catch (Throwable e){
e.printStackTrace();
}
You are making string again toString which having no sense. please do some modification in your code .I have also done changes that you requrie.
String data = JSON TEXT!!!;
JSONObject jRealObject = new JSONObject(data);
String title = jRealObject.getString("title");
String url = jRealObject.getString("url");
String fulltext = jRealObject.getString("fulltext");
JSONObject obj = jRealObject.getJSONObject("fulltext");
String strPage1 = obj.getString("page1");
String strPage2 = obj.getString("page2");
jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
String relatedId = jRealObject.getString("id");
String relatedTitle = jRealObject.getString("title");
String relatedImage = jRealObject.getString("image_name");
}
In my code I'm getting an array using a for loop. The array contains four values. How do I print the values in a textview? I want to print these four values in four textviews.
My Code:
HttpClient client2 = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client2.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client2.getParams(), 15000);
HttpUriRequest request2 = new HttpGet(SelectMenuAPI2);
HttpResponse response2 = client2.execute(request2);
InputStream atomInputStream2 = response2.getEntity().getContent();
BufferedReader in2 = new BufferedReader(new InputStreamReader(atomInputStream2));
String line2;
String str2 = "";
while ((line2 = in2.readLine()) != null) {
str2 += line2;
}
JSONObject json3 = new JSONObject(str2);
// message = json2.getString("message");
status = json3.getString("status");
if (status.equals("1")) {
JSONArray school2 = json3.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object3 = school2.getJSONObject(i);
Elementarytxt.settext("");
Middle.setText("");
High.setText("");
Atypical.setText("");
}
}
My JSON Data:
{
"status":1,
"data":[
{"title":"Elementary"},
{"title":"Middle"},
{"title":"High"},
{"title":"Atypical"}
]
}
JSONArray jsonArray = jObject.getJSONArray(ARRAYNAME);
if (jObject != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
txt.setttext(jsonObject.getString(CREATEDDATE));
txt.setttext(jsonObject.getString(SUBJECT));
}
}
Please check this. It might help you...
String [] mVal = new String[school2.length()];
for (int i = 0; i < school2.length(); i++)
{
mVal[i] =school2.getJSONObject(i).getString("title");
}
Elementarytxt.setText(mVal[0]);
Middle.setText(mVal[1]);
High.setText(mVal[2]);
Atypical.setText(mVal[3]);
I hope This will Help you..
String[] vals=new String[4];
for (int i = 0; i < school2.length(); i++) {
JSONObject object3 = school2.getJSONObject(i);
vals[i]=object3.getString("title");
}
Elementarytxt.settext(vals[0]);
Middle.setText(vals[1]);
High.setText(vals[2]);
Atypical.setText(vals[3]);
I have a web service returning the following string verbatim:
"{\"type\":\"youtube\", \"data\":\"http://66.84.12.156/android/?x=12&uid=4&lati=40.73972412&longi=-73.99234962&y=14&pixel_id=7224&pid=4&surface_id=7&fn=showHTML&data_id=7224&data=kT2UQ8TYMpk\",\"pixel_id\":\"471\",\"x\":\"12\",\"y\":\"14\",\"pid\":\"4\",\"surface_id\":\"7\",\"data_id\":\"7224\",\"user_id\":\"4\"}"
Code looks lke:
dataScanner.client = new DefaultHttpClient();
dataScanner.post = new HttpPost("http://someurl/somepage.php");
post.setEntity(new UrlEncodedFormEntity(userKV));
Log.d("DST Scanner", "post string:" + post.toString());
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line);
}
Log.d("DST Scanner", "Post Response (string)" + builder.toString());
//JSONTokener tokener = new JSONTokener(builder.toString());
finalResult = new JSONObject(builder.toString());
I've tried many different formats (escaped quotes, unescaped quotes, no surrounding quotes, escaped forward slashes), but I keep getting this error:
org.json.JSONException: Value {"type":"youtube", "data":"http://66.84.12.156/android/?x=12&uid=4&lati=40.73972412&longi=-73.99234962&y=14&pixel_id=7224&pid=4&surface_id=7&fn=showHTML&data_id=7224&data=kT2UQ8TYMpk","pixel_id":"471","x":"12","y":"14","pid":"4","surface_id":"7","data_id":"7224","user_id":"4"} of type java.lang.String cannot be converted to JSONObject
Everything looks fine to me, but I've been looking at this so long I wouldn't be surprised if there's some silly thing I'm doing..
I'm new to json, but all of my JSON start and end with "[" and "]" and I use PHP to echo out the json_encode method.
On Android side i use:
try {
URL pHH = new URL("http://192.168.1.5/somephp.php");
URLConnection WC = pHH.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(WC.getInputStream()));
String line;
while((line = in.readLine()) != null){
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++){
JSONObject jo = (JSONObject) ja.get(i);
items[i] = jo.getString("title");
thumbnails[i] = jo.getString("thumb");
links[i] = jo.getString("link");
}
}
char[] utf8 = null;
StringBuilder properString = new StringBuilder("");
utf8 = Response.toCharArray();
for (int i = 0; i < utf8.length; i++) {
if ((int) utf8[i] < 65000) {
properString.append(utf8[i]);
}
}
System.out.println("Response of Login::"
+ properString.toString());