I want to create Json String like this from available data,
Json String:
{
"1": {
"attendance_user_status": 1
},
"2": {
"attendance_user_status": 0
},
"3": {
"attendance_user_status": 1
},
"4": {
"attendance_user_status": 1
},
"5": {
"attendance_user_status": 1
},
"6": {
"attendance_user_status": 0
},
"7": {
"attendance_user_status": 1
}, ...
}
I wrote this java code..
public String jsonCreator(ArrayList<Attendance> attendanceArrayList) throws JSONException {
JSONObject object = new JSONObject();
JSONArray jsonArray = new JSONArray();
for(int i = 0;i<attendanceArrayList.size();i++){
JSONObject objId = new JSONObject();
JSONObject objAtt = new JSONObject();
objAtt.put("attendance_user_status",attendanceArrayList.get(i).getValue());
objId.put(attendanceArrayList.get(i).getId(),objAtt);
jsonArray.put(objId);
}
object.put("user",jsonArray);
return object.toString();
}
But using this code I'm getting this array, Not as I required.
{
"user": [
{
"1": {
"attendance_user_status": "2"
}
},
{
"2": {
"attendance_user_status": "1"
}
},
{
"3": {
"attendance_user_status": "1"
}
},
{
"4": {
"attendance_user_status": "1"
}
}
]
}
I want to append json object but not by json array.
You never initilize json any other than String json = "";, so an empty string will be returned.
You have to get the string from your json object and set it to json.
Do the following at the end of your method:
json = objId.toString();
return json;
Try like this:
public String jsonCreator(ArrayList<Attendance> attendanceArrayList) throws JSONException {
JSONArray jsonArray = new JSONArray();
for(int i = 0;i<attendanceArrayList.size();i++){
JSONObject objId = new JSONObject();
JSONObject objAtt = new JSONObject();
objAtt.put("attendance_user_status",attendanceArrayList.get(i).getValue());
objId.put(attendanceArrayList.get(i).getId(),objAtt);
jsonArray.put(objId);
}
return jsonArray.toString();
}
Related
In my Android app, I am fetching the details of Points table of a tournament to convert the output to a string from JSON object to Java
JSON object is shown below:
{
"group": {
"Teams": [
{
"name": "Team 1",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 2",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 3",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 4",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 5",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 6",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 7",
"p": "10",
"w": "5",
"l": "5",
"points": "11"
},
{
"name": "Team 8",
"p": "10",
"w": "5",
"l": "5",
"points": "11"
}
]
}
}
Android Java Code is below:
JSONObject match = new JSONObject(response);
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONObject teams = group.getJSONObject("Teams");
if (teams.has("0")) {
JSONObject teams_object = teams.getJSONObject("0");
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
But I am getting the error where I print the error message through getMessage() method. Here is the error below:
Error: Value ["name","p","w","l","points"] at header of type org.json.JSONArray cannot be converted to JSONObject
Can anyone please help like where I am going wrong or what is the fix ? Thanks in advance
In your Json Teams holds the Array of Object and you are parsing wrong.
Try this
JSONObject jsonObject = new JSONObject(response);
JSONObject groups = jsonObject.getJSONObject("group");
JSONArray teams = groups.getJSONArray("Teams");
for(int i=0;i<teams.length();i++){
JSONObject obj = teams.getJSONObject(i);
name.append(obj.getString("name")+"\n");
}
There is 4 mistakes in your code,
1.You have to check whether group has teams instead match has teams.
2.You have to get team as JSONArray instead of JSONObject because it is array.
3.You have to check the size of team, instead of find the object with key 0, there is no object with name 0 in your group,
4.You have to get the object based on index instead of key(ie., 0)
Please check the working code, this is tested
try {
JSONObject match = new JSONObject(response);
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (group.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
if (teams.length() > 0) {
JSONObject teams_object =(JSONObject) teams.get(0);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
Log.v(TAG, team_name);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONObject subObject = jsonObject.getJSONObject("group") ;
JSONArray jsonArray = subObject.getJSONArray("Teams");
for (int i=0; i<jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String p= jsonObject.getString("p");
String w= jsonObject.getString("w");
String l= jsonObject.getString("l");
String points = jsonObject.getString("points");
}
} catch (Exception e) {
e.printStackTrace();
}
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
// for only 0th element use below code else looping
JSONObject teams_object = (JSONObject) teams.get(0);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
Error: Value ["name","p","w","l","points"] at header of type
org.json.JSONArray cannot be converted to JSONObject
You are getting the error because there is an Array of Teams and you are trying parse with JSONObject
Please check below code snippet. It will work.
try {
JSONObject match = new JSONObject("your_response");
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (group.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
for(int i=0; i < teams.length(); i++){
JSONObject teams_object = (JSONObject) teams.get(i);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this #SaAsh, I have just edited by taking your answer
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONObject teams = group.getJsonArray("Teams");
for(int i = 0 ; i < teams.length();i++){
JSONObject teams_object = teams.getJSONObject("i");
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
}
if i have a json file like that
{
"users": [{
"name": "aa",
"address": "a"
},
{
"name ": "bb",
"address": "b"
},
{
"name": "cc",
"address": "c"
},
]}
how to read this json file and put all names in a String array in android
i used this code but in second loop it catches exception
public void loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
try {
JSONObject obj = new JSONObject(json);
JSONArray m_jArry = obj.getJSONArray("users");
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
names.add(jo_inside.getString("name"));
images.add(jo_inside.getString("address"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
That Json object 2nd element in the array has space next to name you can solve by 2 ways.
As your backend guys to change that
You solve the problem like this,
Change getString to optString like this
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String name = jo_inside.optString("name");
if(TextUtils.isEmpty(name)) {
name = jo_inside.optString("name "); // that object have space
}
names.add(name);
images.add(jo_inside.getString("address"));
}
Your Json file contain wrong format JSON.
Remove , from the last array element
{
"name": "cc",
"address": "c"
},
The valid Json should be:
{
"users": [{
"name": "aa",
"address": "a"
},
{
"name": "bb",
"address": "b"
},
{
"name": "cc",
"address": "c"
}
]
}
You have problem in your JSON string only. In second JSON name field has extra space. And also there is , after last JSON },
{
"users": [{
"name":"aa",
"address":"a"
},
{
"name":"bb",
"address":"b"
},
{
"name":"cc",
"address":"c"
}
]
}
I have two items in arraylist
Position 0 : product_id=500,amout=1
Position 1 : product_id=501,amout=1
I want to create this type of json
{
"user_id": "3",
"shipping_id": "1",
"payment_id": "2",
"products": {
"500": {
"product_id": "500",
"amount": "1"
},
"501": {
"product_id": "501",
"amount":"1"
}
}
}
This is my code
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_id", usr);
jsonObject.accumulate("shipping_id", shipping_id);
jsonObject.accumulate("payment_id", payment_id);
for( i=0;i<alProductss.size();i++) {
String a = alProductss.get(i).getAnount();
String b = alProductss.get(i).getProduct_id();
JSONObject productObject = new JSONObject();
jsonObject.accumulate("products", productObject);
JSONObject numberObject = new JSONObject();
numberObject.accumulate("product_id", b);
numberObject.accumulate("amount", a);
productObject.accumulate(b, numberObject);
}
I am getting this Responce:
{
"user_id":"230",
"shipping_id":"1",
"payment_id":"14",
"products":[
{"579":
{
"product_id":"579",
"amount":"1"
}
},
{"593":
{
"product_id":"593",
"amount":"1"
}
}]
}
But I want this json Responce please help for getting resultant responce.
{
"user_id": "3",
"shipping_id": "1",
"payment_id": "2",
"products": {
"500": {
"product_id": "500",
"amount": "1"
},
"501": {
"product_id": "501",
"amount":"1"
}
}
}
You can use the following code to generate your JSON,
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_id", usr);
jsonObject.put("shipping_id", shipping_id);
jsonObject.put("payment_id", payment_id);
JSONObject productValueObject = new JSONObject();
for (int i = 0; i < alProductss.size(); i++) {
String a = alProductss.get(i).getAmount();
String b = alProductss.get(i).getProduct_id();
JSONObject projectObj = new JSONObject();
projectObj.put("product_id", b);
projectObj.put("amount", a);
productValueObject.put(b, projectObj);
}
jsonObject.put("products", productValueObject);
} catch (JSONException e) {
e.printStackTrace();
}
try this one..
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_id", usr);
jsonObject.accumulate("shipping_id", shipping_id);
jsonObject.accumulate("payment_id", payment_id);
JSONArray jsonArray = new JSONArray();
for( i=0;i<alProductss.size();i++) {
String a = alProductss.get(i).getAnount();
String b = alProductss.get(i).getProduct_id();
JSONObject productObject = new JSONObject();
JSONObject numberObject = new JSONObject();
numberObject.accumulate("product_id", b);
numberObject.accumulate("amount", a);
jsonArray.put(numberObject);
}
jsonObject.put("products",jsonArray);
Before I parse json json array, but this json object. Its It drove me to a standstill. How i can parse json like this:
{ "test1": {
"1": {
"action": "0",
"type": "1",
"id": "1",
},
"2": {
"action": "0",
"type": "1",
"id": "2",
}
},
"test2": {
"1": {
"id": "1",
"name": "one"
},
"2": {
"id": "2",
"name": "two"
},
"5": {
"id": "5",
"name": "three"
}
}}
When you don't have a fixed set of keys, that you know upfront, the only way to parse it is to use keys(). It returns an Iterator with the keys contained in the JSONObject. In your case you could have
JSONObject jsonObject = new JSONObject(...);
Iterator<String> iterator = jsonObject.keys();
while(iterator.hasNext()) {
String currentKey = iterator.next();
JSONObject obj = jsonObject.optJSONObject(key);
if (obj != null) {
Iterator<String> iterator2 = obj.keys();
}
}
iterator will return test1 and test2, while iterator2 will return 1 and 2, for test1 and 1 ,2 , 5 for test2
You can create a JSONObject From string as bellow
JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);
and to parse the jsonObject
JSONObject test1Json = jsonObject.getJSONObject("test1");
JSONObject oneTest1Json = test1Json.getJSONObject("1");
to get String values
String action = oneTest1Json.getString("action");
String type = oneTest1Json.getString("type");
String id = oneTest1Json.getString("id");
Log.d("Json parse","action -"+action+" type -"+type+" id -"+id);
if need them as JSONArray the you can try
public JSONArray getJsonArray (JSONObject jsonObject){
JSONArray nameJsonArray = jsonObject.names();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < nameJsonArray.length(); i++) {
try {
String key = nameJsonArray.getString(i);
jsonArray.put(jsonObject.getString(key));
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}
in case keys like test1,test2,test3...
JSONObject jsonObject = new JSONObject("{'test1':'Kasun', 'test2':'columbo','test3': '29'}");
JSONArray jsonArray = new JSONArray();
for (int i = 1; i <= jsonObject.names().length(); i++) {
try{
jsonArray.put(jsonObject.getString("test" + i));
}catch (JSONException e){
e.printStackTrace();
}
you can get your JSONArray this way.
I am parsing some JSON that has arrays within arrays, and I just cant seem to get the data of the arrays within the first array.
My JSON looks like this (I cut it off in the end so it wasn't that long):
{"TrackingInformationResponse": {
"shipments": [
{
"shipmentId": "03015035146308",
"uri": "\/ntt-service-rest\/api\/shipment\/03015035146308\/0",
"assessedNumberOfItems": 1,
"deliveryDate": "2013-05-13T11:47:00",
"estimatedTimeOfArrival": "2013-05-13T16:00:00",
"service": {
"code": "88",
"name": "DPD"
},
"consignor": {
"name": "Webhallen Danmark ApS",
"address": {
"street1": "Elsa Brändströms Gata 52",
"city": "HÄGERSTEN",
"countryCode": "SWE",
"country": "Sverige",
"postCode": "12952"
}
},
"consignee": {
"name": "Lene Bjerre Kontor & IT Service",
"address": {
"street1": "Lene Bjerre",
"street2": "Ørbækvej 8, Hoven",
"city": "TARM",
"countryCode": "???",
"postCode": "6880"
}
},
"statusText": {
"header": "Forsendelsen er udleveret",
"body": "Forsendelsen blev leveret 13-05-2013 kl. 11:47"
},
"status": "DELIVERED",
"totalWeight": {
"value": "0.55",
"unit": "kg"
},
"totalVolume": {
"value": "0.005",
"unit": "m3"
},
"items": [
{
"itemId": "03015035146308",
"dropOffDate": "2013-05-08T17:18:00",
"deliveryDate": "2013-05-13T11:47:00",
"status": "DELIVERED",
"statusText": {
"header": "Forsendelsen er udleveret til modtageren",
"body": "Forsendelsen blev udleveret 13-05-2013 kl. 11:47"
},
I can get the content of the "shipments" array just fine, but I have no idea how to get the contents of the "items" array. My code looks like this:
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
How would I do the same with the "items" array as I did with the "shipments" array?
You have to get the items array from inside the Shipment array, like you did the shipments, then iterate through that, like you did the shipments.
It might look something like:
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items");
//get items stuff
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
items is a JSON Array located inside the shipments array, so you need to get the items array within the shipments, maybe like this :
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items"));
//iterate over items
}
Hope this helps, Good luck
Try bellow code:
JSONObject jObject = new JSONObject(yourJSONString);
JSONObject trackInfo = jObject.getJSONObject("TrackingInformationResponse");
JSONArray shipMents = trackInfo.getJSONArray("shipments");
JSONArray items = shipMents.getJSONArray("items");