POST JSON array with indices using retrofit - android

I'm using retrofit to POST a json array to server. Data is something like this:
{something:
{somethings:
[
{"param1":"value", "param2":value},
{"param1":"value", "param2":value}
]
}
}
however, my server forces me to MUST include the indices in the array like:
{something:
{somethings:
{
"0":{"param1":"value", "param2":value},
"1":{"param1":"value", "param2":value}
}
}
}
In other words cannot send parameters like this:
something[somethings][][param1]
something[somethings][][param2]
I must include indices:
something[somethings][0][param1]
something[somethings][0][param2]
How to do this using retrofit?
My interface looks like this:
interface ApiService {
#POST("endpoint")
public Callback<Something> postSomething (#Body Something something);
}
My classes look like following:
public class PostSomething {
private MapOfSomething something = new MapOfSomething();
public MapOfSomething getSomething() {
return portfolio;
}
public void setSomething(MapOfSomething something) {
this.something = something;
}
}
public class MapOfSomething {
private JSONObject somethings = new JSONObject();
public JSONObject getPortfolios() {
return somethings;
}
public void setSomethings(List<Something> somethingList) {
for (int i = 0; i<somethingList.size(); i++) {
try {
somethings.put(String.valueOf(i).toString(), somethingList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and calling the method like:
PostSomethings something = new PostSomethings();
MapOfSomething map = new mapOfSomething();
map.setSomethings(listofSomething);
something.setSomethings(map);
apiService.postSomething(something);

One way to solve your problem is to put json directly into body , so your interface will look like this
interface ApiService {
#POST("endpoint")
public Callback<Something> postSomething (#Body JSONObject jsonObject);
}
Now you need to create the JSONObject , here is how I have created your desired JSONObject
JSONObject mainJson = new JSONObject();
JSONArray list = new JSONArray();
JSONObject singleElement1 = new JSONObject();
try {
singleElement1.put("param1","value1");
singleElement1.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElementSet1 = new JSONObject();
try {
singleElementSet1.put("1",singleElement1);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElement2 = new JSONObject();
try {
singleElement2.put("param1","value1");
singleElement2.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElementSet2 = new JSONObject();
try {
singleElementSet2.put("2",singleElement2);
} catch (JSONException e) {
e.printStackTrace();
}
list.put(singleElementSet1);
list.put(singleElementSet2);
JSONObject subJson = new JSONObject();
try {
subJson.put("something",list);
mainJson.put("something",subJson);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("json",""+mainJson.toString());
I am assuming right now you are calling your service like this way
Call<Something> call = instanceOfYourAPIService.postSomething(anInstanceOfSomethingObject);
But now you have to replace this with the following
Call<Something> call = instanceOfYourAPIService.postSomething(mainJson); //mainJson is the JSONObject which is created earlier
Hope it helps
EDIT
JSONObject mainJson = new JSONObject();
JSONObject singleElement1 = new JSONObject();
try {
singleElement1.put("param1","value1");
singleElement1.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElement2 = new JSONObject();
try {
singleElement2.put("param1","value1");
singleElement2.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
ArrayList<JSONObject> jsonObjectArrayList = new ArrayList<JSONObject>();
//hope you can add item to this arraylist via some loop
jsonObjectArrayList.add(singleElement1);
jsonObjectArrayList.add(singleElement2);
JSONArray list = new JSONArray();
for(int i = 0;i<jsonObjectArrayList.size();i++){
JSONObject elementSet = new JSONObject();
try {
elementSet.put(String.valueOf(i).toString(),jsonObjectArrayList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
list.put(elementSet);
}
JSONObject subJson = new JSONObject();
try {
subJson.put("something",list);
mainJson.put("something",subJson);
} catch (JSONException e) {
e.printStackTrace();
}

Related

Android studio web socket - Error receiving multiple JSON objects at once

I am struggling with something that really p*sses me off for several hours.
My android app manages to connect to a websoket, and receives json data which for now has worked perfectly, and here is the code for this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
This code above as I said works perfectly, and i get the data in everytime. HOWEVER, HOWEVER, HOWEVER: If i try to receive 2 json-objects at the sametime through this emittener, it does not work!!!!
Here is example when i try to receive multiple JSON objects, and NONE of them works!
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetFromSensor = new JSONObject( (String) args[0]);
int targetNum = incomingTargetFromSensor.getInt("target_number_count");
showTargetRep(targetNum); //NOT WORKING!
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position); //NOT WORKING!
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
In the first example I could receive the position data, and the code is exactly similar as the example above, but for some reasons it can not recevice data when i try to receive another JSON object.
Another example of why I always disliked JSON object.
Any help plz?
The solution at the end was to add multiple try/catches like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetRepFromSensor = new JSONObject((String ) args[0]);
int target_rep = incomingTargetRepFromSensor.getInt("target_repetition_count");
showTargetRep(target_rep);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingDataFromSensor = new JSONObject((String ) args[0]);
double the_position = incomingDataFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingTargetSetFromSensor = new JSONObject((String ) args[0]);
int target_set = incomingTargetSetFromSensor.getInt("target_set_count");
showTargetSet(target_set);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingRepsFromSensor = new JSONObject((String ) args[0]);
int the_repetitions = incomingRepsFromSensor.getInt("repetitions");
showCurrentReps(the_repetitions);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingSetsFromSensor = new JSONObject((String ) args[0]);
int the_sets = incomingSetsFromSensor.getInt("sets");
showCurrentSets(the_sets);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}

org.json.JSON.typeMismatch(JSON.java:111)

I am getting a org.json.JSON.typeMismatch(JSON.java:111) error while trying to create a JSON array. The received data looks like this:
{
"result":[
{
"#type":"d",
"#rid":"#-2:0",
"#version":0,
"a_adres":"kepez merkez geliyor herkez",
"takipkodu":"464664",
"agirlik":50
},
{
"#type":"d",
"#rid":"#-2:1",
"#version":0,
"a_adres":"merkez mahallesi 4 sok",
"takipkodu":"sd4fs654f64",
"agirlik":60
}
]
}
Code:
protected String doInBackground(String... urls) {
try {
String getResponse = get("http://178.18.206.128:2480/command/nakliye/sql/select a_adres,takipkodu,agirlik from yukilan");
return getResponse;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String getResponse) {
ListView liste=(ListView)findViewById(R.id.list_view);
try {
JSONArray yukilanarray = new JSONArray(getResponse);
List<Yukilan> yukilanlar = new ArrayList<>();
//Populate the EmployeeDetails list from response
for (int i = 0; i<yukilanarray.length();i++){
Yukilan yeniilan = new Yukilan();
JSONObject yukilanobject = yukilanarray.getJSONObject(i);
yeniilan.setAdres(yukilanobject.getString(KEY_ADRES));
yeniilan.setAgirlik(yukilanobject.getString(KEY_AGIRLIK));
yeniilan.setTakip_kod(yukilanobject.getString(KEY_TAKIPKODU));
yukilanlar.add(yeniilan);
}
//Create an adapter with the EmployeeDetails List and set it to the LstView
yukilanadapter = new Yukilanadapter(yukilanlar,getApplicationContext());
liste.setAdapter(yukilanadapter);
} catch (JSONException e) {
e.printStackTrace();
}
// System.out.println(getResponse);
}
Please help.
I think you made a mistake in reading the json. the first element would be a JSONObject not a JSONArray.Below is the revised code.
protected String doInBackground(String... urls) {
try {
String getResponse = get("http://178.18.206.128:2480/command/nakliye/sql/select a_adres,takipkodu,agirlik from yukilan");
return getResponse;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String getResponse) {
ListView liste=(ListView)findViewById(R.id.list_view);
try {
JSONObject jsonObject = new JSONObject(getResponse);
JSONArray yukilanarray = jsonObject.getJSONArray("result");
List<Yukilan> yukilanlar = new ArrayList<>();
//Populate the EmployeeDetails list from response
for (int i = 0; i<yukilanarray.length();i++){
Yukilan yeniilan = new Yukilan();
JSONObject yukilanobject = yukilanarray.getJSONObject(i);
yeniilan.setAdres(yukilanobject.getString(KEY_ADRES));
yeniilan.setAgirlik(yukilanobject.getString(KEY_AGIRLIK));
yeniilan.setTakip_kod(yukilanobject.getString(KEY_TAKIPKODU));
yukilanlar.add(yeniilan);
}
//Create an adapter with the EmployeeDetails List and set it to the LstView
yukilanadapter = new Yukilanadapter(yukilanlar,getApplicationContext());
liste.setAdapter(yukilanadapter);
} catch (JSONException e) {
e.printStackTrace();
}
// System.out.println(getResponse);
}

Android - How to parse intent to json object?

I want to add my intent to json object, but how to do that with this code below
Pojo.java
//getter and setter on above code
JSONObject obj = new JSONObject();
try {
obj.put("id", id);
obj.put("nilai", ratingStar);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
Main.java
for (int i=0;i<size;i++){
jArray.put(adapter3.getItem(i).getJsonObject());
}
JSONObject j=new JSONObject();
try {
j.put("fishing",jArray);
Log.d("json output : ",j.toString());
} catch (JSONException e) {
e.printStackTrace();
}
And the respone from Log.d("json output : ",j.toString()); is :
{"fishing":[{"id":"1","nilai":1},{"id":"2","nilai":1},{"id":"3","nilai":1},{"id":"4","nilai":1},{"id":"5","nilai":1}]}
But i want to add my intent into json object like this
{"fishing":[{|"id_dosen":"2","id_matkul":"3"|,"id":"1","nilai":1},{|"id_dosen":"2","id_matkul":"3"|,"id":"2","nilai":1},{|"id_dosen":"2","id_matkul":"3"|,"id":"3","nilai":1},{|"id_dosen":"2","id_matkul":"3"|,"id":"4","nilai":1},{|"id_dosen":"2","id_matkul":"3"|,"id":"5","nilai":1}]}
can someone help me how to add the json that I mark with |??
Note : i use | symbol just to let you guys easy to read what's the different from 1st json with 2nd json
You can simply add those fields in your JSON like this.
String jsonFishing = "{\"fishing\":[{\"id\":\"1\",\"nilai\":1},{\"id\":\"2\",\"nilai\":1},{\"id\":\"3\",\"nilai\":1},{\"id\":\"4\",\"nilai\":1},{\"id\":\"5\",\"nilai\":1}]}";
try {
JSONObject rootObj = new JSONObject(jsonFishing);
JSONArray fishingArr = rootObj.getJSONArray("fishing");
for (int i = 0; i < fishingArr.length(); i++){
JSONObject child = fishingArr.getJSONObject(i);
child.put("id_dosen", 2);
child.put("id_matkul", 3);
}
...
yourIntent.putExtra("json", rootObj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Newly obtained JSON looks like this.
{"fishing":[{"id":"1","nilai":1,"id_dosen":2,"id_matkul":3},{"id":"2","nilai":1,"id_dosen":2,"id_matkul":3},{"id":"3","nilai":1,"id_dosen":2,"id_matkul":3},{"id":"4","nilai":1,"id_dosen":2,"id_matkul":3},{"id":"5","nilai":1,"id_dosen":2,"id_matkul":3}]}
Edit : In your code, it would be like this
for (int i=0;i<size;i++){
JSONObject jsonObject = adapter3.getItem(i).getJsonObject();
jsonObject.put("id_dosen", 2);
jsonObject.put("id_matkul", 3);
jArray.put(jsonObject);
}
Hope this helps :)

Android build a jsonarray of jsonobjects

I'd like to build a json object which contains, among others, an array of objects like this:
{"ChoisiEvents":[{"Id_evt":25},{"Id_evt":4}],"parasite":3}
I have written some code like :
JSONArray JAChoisiEvents = new JSONArray();
JSONObject objEvent = new JSONObject();
try{
if (cbxTemp.isChecked()){
objEvent.put("Id_evt", 25);
JAChoisiEvents.put(objEvent);
}
if (cbxAutreRaison.isChecked()) {
objEvent.put("Id_evt", 4);
JAChoisiEvents.put(objEvent);
}
} catch (JSONException e) {
e.printStackTrace();
}
//...
JSONObject obj = new JSONObject();
try {
obj.put("parasite", iParasite);
System.out.println("ChoisiEvents : " + JAChoisiEvents.toString());
obj.put("ChoisiEvents", JAChoisiEvents); //
} catch (JSONException e) {
e.printStackTrace();
}
I got the following result:
{"ChoisiEvents":[{"Id_evt":4},{"Id_evt":4}],"parasite":3}
As you can see, the last item in my array is repeated each time !
You are using the same JSONObject, thats why value is overriding,
try to instantiate for the second time
objEvent = new JSONObject();
After adding to the first value.
Like this
JSONObject objEvent;
if (cbxTemp.isChecked()){
objEvent = new JSONObject();
objEvent.put("Id_evt", 25);
JAChoisiEvents.put(objEvent);
}
if (cbxAutreRaison.isChecked()) {
objEvent = new JSONObject();
objEvent.put("Id_evt", 4);
JAChoisiEvents.put(objEvent);
}

Android - get data from json

I have a api call that returns this json object:
{
"elenco": [
"folder 1",
"folder 2",
"folder 3"
],
"codice": "123456789"
}
and this is my piece of code that get the result:
protected void onPostExecute(JSONObject result) {
// Close progress dialog
Dialog.dismiss();
JSONObject jobj = null;
String codice_utente = null;
JSONArray elenco_cartelle = null;
try {
jobj = new JSONObject(String.valueOf(result));
} catch (JSONException e) {
e.printStackTrace();
}
//Provo a recuperare i campi json
try {
codice_utente = jobj.getString("codice");
elenco_cartelle = jobj.getJSONArray("elenco");
} catch (JSONException e) {
e.printStackTrace();
}
//This should fetch the elenco array
for (int i = 0; i < elenco_cartelle.length(); i++) {
JSONObject childJSONObject = null;
try {
childJSONObject = elenco_cartelle.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
//Can't use getString here...
}
}
How can I fetch the elenco part? I do not have a key to use, so how can I add every row in an ArrayList?
I tried to use a for but I have no idea about how to get the rows
Use JSONArray.getString() http://developer.android.com/reference/org/json/JSONArray.html#getString(int)
for (int i = 0; i < elenco_cartelle.length(); i++) {
String content = null;
try {
content = elenco_cartelle.getString(i);
} catch (JSONException e) {
e.printStackTrace();
}
//Can't use getString here...
}
You now have your content on content

Categories

Resources