Converting array list object to jsonarray - java

I have arraylist that needs to be converted to json array to post in the server
the format of json should be like this:
{
p:1,
s:["a":1,"b":2],["a":2,"b":3],["a":3,"b":4]
}
Let say I have:
List<MyObject> objectList = new ArrayList<MyObject>();
MyObject myObject = new MyObject();
myObject .setA(1);
myObject .setB(2);
myObject .setA(2);
myObject .setB(3);
myObject .setA(3);
myObject .setB(4);
objectList.add(myObject);
My current code is:
for (int i = 0; i < objectList.size(); i++) {
JSONArray ar = new JSONArray();
ar.put("a:"+objectList.get(i).getA());
ar.put("b:"+objectList.get(i).getB());
jOuter.put("s",ar);
}
but this doesnt work, the current return is:
{"p":1,"s":["a:20","b:10.0"]}
Thanks.

Shouldn't it be something like this?
JSONArray ar = new JSONArray();
for (int i = 0; i < objectList.size(); i++) {
JSONObject objects = new JSONObject();
objects.put("a", objectlist.get(i).getA();
objects.put("b", objectlist.get(i).getB();
ar.put(objects);
}
jOuter.put("s",ar);

Your s entry is actually a JsonArray, while your p is just a property. Here I am using Gson but you could easily apply it to whichever library you are using. So you can do the following:
JsonObject jObj = new JsonObject();
jObj.addProperty("p", 1);
JsonArray sArr = new JsonArray();
for (int i = 0; i < objectList.size(); i++)
{
JsonObject innerObj = new JsonObject();
innerObj.addProperty("a:"+objectList.get(i).getA());
innerObj.addProperty("b:"+objectList.get(i).getB());
sArr.add(innerObj);
}
jObj.addProperty("s", sArr);
The output is:
{
"p":1,
"s":[{"a":1,"b":2},{"a":3,"b":4}]
}

Your required format is invalid.
I think you are looking for something like this
{
"p": 1,
"s": [
{
"a": 1,
"b": 2
},
{
"a": 2,
"b": 3
},
{
"a": 3,
"b": 4
}
]
}
For this code will be like as below
JSONArray jArray = new JSONArray();
for (int i = 0; i < objectList.size(); i++) {
JSONObject job= new JSONObject();
job.put("a",objectList.get(i).getA());
job.put("b",objectList.get(i).getB());
jArray .put(job);
}
try {
jOuter.put("s", jArray );
} catch (JSONException e) {
e.printStackTrace();
}

Please check following code: This will make the proper formatting:
JSONObject jo = new JSONObject();
try {
jo.put("p", "1");
JSONArray jarr = new JSONArray();
for (MyObject listItem : objectList) {
JSONObject inner = new JSONObject();
inner.put("a", listItem.getA());
inner.put("b", listItem.getB());
jarr.put(inner);
}
jo.put("s", jarr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It will return output like:
{
"p":1,
"s":[{"a":1,"b":2},{"a":2,"b":3},{"a":3,"b":4}]
}
This makes a proper json, which I think you need! Do let me know, if I am wrong somewhere.

Related

Parse json in Java android studio

I have this code to parse a json in Java, but problem is my json looks like this
{"ime":"Alen","prezime":"Osmanagi\u0107","test":[1,2,3,4,5],"test2":{"1":"test","2":"555","test":"888","om":"hasd"}}
And my java code for parsing looks like :
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListView listView =(ListView)findViewById(R.id.jsonList);
if ( true) {
try {
JSONArray mojNiz = response.getJSONArray("");
List<JSON> noviJSON = new ArrayList<>();
//Popuniti podacima
for (int i = 0; i < mojNiz.length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = mojNiz.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
// jsonObj.setPrezime(mojObj.getString(KEY_DOB));
//jsonObj.setPrezime(mojObj.getString(KEY_DESIGNATION));
noviJSON.add(jsonObj);
}
adapter = new Adapter(noviJSON, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,
"Problem u loadiranjuz podataka",
Toast.LENGTH_LONG).show();
}
How can I parse this particular json string ???
First get the JSONObject and then the array inside it
JSONObject jsonObject = new JSONObject(jsonString);
String objectIme = jsonObject.getString("ime");
String prezime = jsonObject.getString("prezime");
The above line will get the whole object and from this object you can get other objects and the array test1 and test2 like below then you can loop through that array like you did
JSONArray jArray1 = new JSONArray(jsonObject.getJSONArray("test1"));
JSONArray jArray2 = new JSONArray(jsonObject.getJSONArray("test2"));
for (int i = 0; i < jArray1 .length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = jArray1.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
}
You are parsing your json wrong. Your json starts with jsonObject instead of jsonArray. So in your case you have to start like this
(assuming that your result variable of onPostExecute method has the json string)
JSONObject mojNiz = new JSONObject(result);
Now from the above mojNiz object you can get your json array
String s = "{\"ime\":\"Alen\",\"prezime\":\"Osmanagi\\u0107\",\"test\":[1,2,3,4,5],\"test2\":{\"1\":\"test\",\"2\":\"555\",\"test\":\"888\",\"om\":\"hasd\"}}";
try {
JSONObject jsonObject = new JSONObject(s);
jsonObject.getString("ime");
jsonObject.getString("prezime");
JSONArray jsonArray = jsonObject.getJSONArray("test");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add((Integer) jsonArray.get(i));
}
JSONObject testObject = jsonObject.getJSONObject("test2");
testObject.getString("1");
testObject.getString("2");
} catch (JSONException e) {
e.printStackTrace();
}

ArrayList of Strings to JSON

I have an ArrayList that contains values as follows
"One"
"Two"
"Three" etc.
I am trying to generate an JSON Object / Array out of this. My code is below:
peopleNames = personAdapter.getArrayListNames();
peoplePhones= personAdapter.getArrayListPhones();
JSONNames = new JSONObject();
JSONPhones = new JSONObject();
for (int i = 0; i < peopleNames.size(); i++){
try {
System.out.println(peopleNames.get(i));
JSONNames.put("Name",peopleNames.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < peoplePhones.size(); i++){
try {
JSONPhones.put("Phone",peoplePhones.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
jsonArrayNames = new JSONArray();
System.out.println(jsonArrayNames.toString());
However my output is just:
[{"Name":"One"}]
Why don't you merge the data ? I think, from your adapter, you're able to get people directly, right ? If so, I propose you the following :
people = personAdapter.getPersons();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < people.size(); i++) {
JSONObject object = new JSONObject();
object.put("Name", people.name());
object.put("Phone", people.phone());
jsonArray.put(object);
}
The resulted JSON will be :
[
{"Name":"One",
"Phone": "OnePhone"},
{"Name":"Two",
"Phone": "TwoPhone"},
]

How to parse JSON Array of String in android

this is the response from the server
{"route":[1,2,3,4,5,6]}
This is my code:
try{
String d = json.getString("route");
}
}catch(JSONException je){
}
and im getting NullPointerException.
please help me.
This is my Server Response, Now Give me the solution
Link -> http://ajax.tpksym.cloudbees.net/route/route14
It should be like:
JSONObject jsonResult = new JSONObject("{\"route\":[1,2,3,4,5,6]}");
JSONArray array = jsonResult.getJSONArray("route");
for (int i = 0; i < array.length(); i++) {
int data = array.getInt(i);
}
....
try {
String jsonString = "{\"route\":[1,2,3,4,5,6]}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("route");
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println(jsonArray.getInt(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Hi as yours json is as follows
{
"route": [
1,
2,
3,
4,
5,
6
]
}
so do as follows
String jsondata = "{\"route\":[1,2,3,4,5,6]}";
JSONObject primaryObject = new JSONObject(jsondata);
JSONArray jarray = primaryObject.getJSONArray("route");
for (int i = 0; i < jarray.length(); i++) {
Integer data = jarray.getInt(i);
System.out.println("data=="+data);
}
as you gave the link http://ajax.tpksym.cloudbees.net/route/route14
and data seems there coming as in double i.e. 13.56 etc
so use as follows
String jsondata = "JSON DATA FROM SERVER";
JSONObject primaryObject = new JSONObject(jsondata);
JSONArray jarray = primaryObject.getJSONArray("route");
for (int i = 0; i < jarray.length(); i++) {
Double data = jarray.getDouble(i);
}

Parsing JSON Not Showing out of range

I'm working on parsing JSON file in my java and the JSON file goes like this
{"System":[{"System1":{"DisplayName":"fabcd","InternalName":"AD","SystemCode":"0001","SystemName":"vnid"},"System2":{"DisplayName":"akdfkajfl","InternalName":"AD","SystemCode":"0001","SystemName":"kjdfkafdk"}}]}
I cannot access the all objects inside "System" array. Please help me on this. My code is this
Systems = jObj.getJSONArray("System");
Log.d("Array", Systems.toString());
JSONObject first = Systems.getJSONObject(0);
Log.d("CSystems",first.toString());
// looping through All Contacts
for(int i = 0; i <=Systems.length(); i++){
JSONObject c = Systems.getJSONObject(i);
Log.d("SubSystems", Systems.getString(0));
}
Thanks.
Shouldn't for loop be looping over first instead of Systems? (With changes to account for the fact it's an object, not an array.)
To parse
try
{
JSONObject jObj = new JSONObject("My Json string");
JSONArray jr = jObj.getJSONArray("System");
JSONObject jb= jr.getJSONObject(0);
JSONObject system1 = jb.getJSONObject("System1");
String name = system1.getString("DisplayName");
String internalname = system1.getString("InternalName");
String SystemCode = system1.getString("SystemCode");
String SystemName = system1.getString("SystemName");
JSONObject system2 = jb.getJSONObject("System2");
String name1= system2.getString("DisplayName");
String internalname1 = system2.getString("InternalName");
String SystemCode1 = system2.getString("SystemCode");
String SystemName1 = system2.getString("SystemName");
Log.i("..........",name+"..."+internalname+"..."+SystemCode+"..."+SystemName);
Log.i("..........",name1+"..."+internalname1+"..."+SystemCode1+"..."+SystemName1);
}catch(Exception e)
{
e.printStackTrace();
}
or
Same as above.
try
{
JSONObject jObj = new JSONObject("My json string");
JSONArray jr = jObj.getJSONArray("System");
for(int i = 0; i<jr.length(); i++){
JSONObject c = jr.getJSONObject(i);
for(int j = 1;j<3; j++){
JSONObject jb = c.getJSONObject("System"+(j));
Log.i("SubSystems", jb.getString("DisplayName"));
Log.i("SubSystems", jb.getString("InternalName"));
Log.i("SubSystems", jb.getString("SystemCode"));
Log.i("SubSystems", jb.getString("SystemName"));
}
}
}catch(Exception e)
{
e.printStackTrace();
}
or change your json to
{
"System": [
{
"DisplayName": "fabcd",
"InternalName": "AD",
"SystemCode": "0001",
"SystemName": "vnid"
},
{
"DisplayName": "akdfkajfl",
"InternalName": "AD",
"SystemCode": "0001",
"SystemName": "kjdfkafdk"
}
]
}
To parse. Changing json to above parsing is much more easier.
try
{
JSONObject jObj = new JSONObject("My json string);
JSONArray jr = jObj.getJSONArray("System");
for(int i = 0; i<jr.length(); i++){
JSONObject c = jr.getJSONObject(i);
Log.i("SubSystems", c.getString("DisplayName"));
Log.i("SubSystems", c.getString("InternalName"));
Log.i("SubSystems", c.getString("SystemCode"));
Log.i("SubSystems", c.getString("SystemName"));
}
}catch(Exception e)
{
e.printStackTrace();
}
You can also look at https://code.google.com/p/google-gson/

How to convert string json to JSONArray?

How can I convert this string into JSONArray ?
{"result":{"passion":[{"id":2,"description":"Sushi"},{"id":3,"description":"Dinner"},{"id":4,"description":"Sex"},{"id":5,"description":"Boobies"},{"id":6,"description":"Sleep"},{"id":7,"description":"Cars"},{"id":8,"description":"Travel"},{"id":9,"description":"Soccer"},{"id":10,"description":"Silice"}]}}
I'm trying to do:
JSONArray jsonArray = jsonObject.getJSONArray("passion");
But I am getting an exception:
org.json.JSONException: No value for passion
is seems like you are not getting result object
JSONArray jsonArray = jsonObject. getJSONObject("result").getJSONArray("passion");
may be this is what you need dear
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Use this code
JSONObject jsonObject = new JSONObject(json);
JSONObject resultValues = jsonObject.getJSONObject("result");
JSONArray passionArray = resultValues.getJSONArray("passion")

Categories