How to create Json from Arraylist value? - android

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

Related

error type JSONArray cannot be converted to JSONObject

I'm creating an app to get posts from a web server, and i'm getting a jsonarray to object error I'm new to android development and tutorials i see the JsonArray is named before, so it'd be array of dogs, and then inside that would have breed and name and so on, mines not named.
the code i have is
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try{
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(JSONURL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while(data !=-1){
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(urlConnection !=null){
urlConnection.disconnect();;
}
}
}catch (Exception e){
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("");
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject1= jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Displaying the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
postList,
R.layout.item,
new String[]{"name", "post"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
the json code i'm trying to parse is
[
{
"0": "2",
"id": "2",
"1": "anon",
"name": "anon",
"2": "goodbye people of skivecore",
"post": "goodbye people of skivecore",
"3": "38.751053",
"lat": "38.751053",
"4": "-90.432915",
"lng": "-90.432915",
"5": "",
"ip": "",
"6": "6.204982836749738",
"distance": "6.204982836749738"
},
{
"0": "1",
"id": "1",
"1": "anon",
"name": "anon",
"2": "hello people of skivecore",
"post": "hello people of skivecore",
"3": "38.744453",
"lat": "38.744453",
"4": "-90.607986",
"lng": "-90.607986",
"5": "",
"ip": "",
"6": "9.280600590285143",
"distance": "9.280600590285143"
}
]
and stacktrace message
2021-04-28 23:45:02.156 20352-20352/com.skivecore.secrets W/System.err: org.json.JSONException: Value [{"0":"2","id":"2","1":"anon","name":"anon","2":"goodbye people of skivecore","post":"goodbye people of skivecore","3":"38.751053","lat":"38.751053","4":"-90.432915","lng":"-90.432915","5":"","ip":"","6":"6.204982836749738","distance":"6.204982836749738"},{"0":"1","id":"1","1":"anon","name":"anon","2":"hello people of skivecore","post":"hello people of skivecore","3":"38.744453","lat":"38.744453","4":"-90.607986","lng":"-90.607986","5":"","ip":"","6":"9.280600590285143","distance":"9.280600590285143"}] of type org.json.JSONArray cannot be converted to JSONObject
You should use like below
try {
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
}
I think here is the issue JSONObject jsonObject = new JSONObject(s); as I can see your response is a JSONArray because it has [ and ] at the beginning and the end.
So, I think this would be more appropriate.
try{
JSONArray jsonArray = jsonObject.getJSONArray(s);
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject1= jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
}
please usding gson library To use jasonArray And JsonObject Easley
1). https://github.com/google/gson
2). libraby import then use
https://www.jsonschema2pojo.org/
for your jsonArray to Model class
Then Use jsonArray
Use this instead....
try {
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//put to hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();

Parsing json (android) [duplicate]

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.

Parsing string to json on android

How to parse HTTP response ton JSON object ?
I changed my json code to:
{
"data": [{
"id": 1,
"sensor1": 76,
"sensor2": 75
}, {
"id": 2,
"sensor1": 76,
"sensor2": 206
}]
}
And my code is now:
JSONObject json = new JSONObject(mJson);
try {
data = json.getJSONArray("data");
for (int i = 0; i < json.length(); i++) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
JSONObject obj = (JSONObject) data.get(i);
map.put(TAG_SENSOR_1, obj.getInt("sensor1"));
map.put(TAG_SENSOR_2, obj.getInt("sensor2"));
dataList.add(data.getInt("id") - 1, map);
}
} catch (JSONException e) {
e.printStackTrace();
}
But I have the same problem
edit your string to this format
{content:[{
first:1,
second:76,
third:75
},
{
first:2,
second:76,
third:75
},
{
first:3,
second:206,
third:75
},
{
first:4,
second:6,
third:175
},
{
first:5,
second:176,
third:75
}]
}
then use JSONObject and JSONArray to convert string
JSONArray array = new JSONObject(string).getJSONArray("content");
for(int i=0;i<array.size();i++){
JSONObject obj = array.get(i);
Log.i(TAG,"obj.getInt = "+obj.getInt("first"));
Log.i(TAG,"obj.getInt = "+obj.getInt("second"));
Log.i(TAG,"obj.getInt = "+obj.getInt("third"));
}

Android Json parsing with complicated arrays

[
{
"countries": [
{
"id": 1,
"country": "India"
},
{
"id": 2,
"country": "Australia"
},
{
"id": 3,
"country": "Srilanka"
},
{
"id": 4,
"country": "Pakistan"
},
{
"id": 5,
"country": "Switzerland"
}
]
}
]
How to parse this Json Response in Android. i am not getting any proper solution.
please help me.
Do it like this...
JSONArray arr = locs.getJSONArray("countries");
for (int i = 0; i < arr.length(); ++i) {
JSONObject rec = arr.getJSONObject(i);
int id = rec.getInt("id");
String con = rec.getString("country");
// ...
}
JSONArray jArr=new JSONArray(response);
for(int i=0;i<jArr.length;i++)
{
id[]=jArr.getJSONObject(i).getInt("id");
con[]=jArr.getJSONObject(i).getString("country");
}
http://developer.android.com/reference/org/json/JSONTokener.html
I've also seen Jackson used in Android apps.
JSONArray countriesobj = new JSONArray();
JSONObject json;
try {
JSONObject jObject = new JSONObject(response);
json = jObject;
countriesobj = json.getJSONArray("countries");
country = new String[countriesobj.length()];
for (int i = 0; i < countriesobj.length(); i++) {
JSONObject e = countriesobj.getJSONObject(i);
country[i] = e.getString("country");
}
} catch (Exception e) {
e.printStackTrace();
}

How to parse nested JSON object using the json library?

i want to parse the json object using json library.
{
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
}
}
Using JSON..
JSONObject object = new JSONObject(yourString);
JSONObject batters = object.getJSONObject("batters");
JSONArray batter = batters.getJSONArray("batter");
for(int i = 0 ; i < batter.length() ; i++) {
JSONObject object1 = (JSONObject) batter.get(i);
String id = object1.getString("id");
}
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea"}
]
}
Here below I am fetching country details
JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}

Categories

Resources