Android - get data from json - android

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

Related

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

How to put json array in json object

This is code which I'm using:
#Override
protected String doInBackground(String... arg0) {
String yourJsonStringUrl = "GetCalender_Events";
JsonParser jParser = new JsonParser();
json = jParser.getJSONFromUrlArray(yourJsonStringUrl);
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"), c.getString("Event_Name"),
sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),
c.getString("Description")));
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
How to put my JSON Array into JSON object? Can anyone please help me, this is my first try with JSON Array.
My array looks like this:
{
"ContactList": [
{
"Column1": "22-05-2017",
"Event_Name": "Garba Compition",
"Description": "School organized garba compition"
},
{
"Column1": "24-05-2017",
"Event_Name": "Mahendi Compition",
"Description": "Mahendi compition"
}
]
}
#. Seems you are getting JSONObject as response. So you have to parse JSONObject first from sever response:
JSONObject json = jParser.getJSONFromUrlObject(yourJsonStringUrl);
#. Then parse ContactList and its item as below:
#Override
protected void onPostExecute(String strFromDoInBg) {
JSONArray jsonArray = json.getJSONArray("ContactList");
for (int i = 0; i < jsonArray.length(); i++) {
try
{
JSONObject c = jsonArray.getJSONObject(i);
ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"),c.getString("Event_Name"), sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),c.getString("Description")));
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
JSONArray jsonarray = new JSONArray();
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put(jsonarray);
} catch(JSONException e){
e.printStackTrace();
}
You get the values
JSONArray songobj = json.getJSONArray("ContactList");
Log.d(TAG, "List Length" + songobj.length());
for (int i = 0; i < songobj.length(); i++) {
JSONObject song = songobj.getJSONObject(i);
String column=song.getString("Column1");
String name=song.getString("Event_Name");
String desc=song.getString("Description");
ldatosAgenda.add(new DatosAgenda(column,name,desc));
}
}

POST JSON array with indices using retrofit

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

how to parse JSON array (Language array )?

I want to fetch string values from a JSON-array and set it to a spinner in Android. How can I
do this?
`{"languages":["English","Hindi","Punjabi","",""]} `languages":["English","Hindi","Punjabi","",""]}
You can parse your JSONARRAY like this
if (jsonResultArry != null) {
for (int i = 0; i < jsonResultArry.length(); i++) {
try {
JsonObject jsonPblm = jsonResultArry.getJSONObject(i);
pblmId = jsonPblm.getString("id");
ticketDate = jsonPblm.getString("ticket_date");
pblmName = jsonPblm.getString("description");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

How do i convert from this org.json into jackson parser?

JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jsonArray = jsonObj.getJSONObject("query").getJSONObject("results").getJSONArray("row");
int arrayCount = jsonArray.length();
for(int i=0; i < arrayCount; i++){
JSONObject jsonData = jsonArray.getJSONObject(i);
String col0 = jsonData.getString("col0");
String col1 = jsonData.getString("col1");
// etc, etc ...
// put those values in arrays or whatever here.
}
What is the syntax for the same operation but using the 'Jackson' parsing libary?
I currently have:
JsonFactory f = new MappingJsonFactory();
JsonParser jp = f.createParser(res);
JsonToken current;
current = jp.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
// move from field name to field value
current = jp.nextToken();
if (fieldName.equals("row")) {
if (current == JsonToken.START_ARRAY) {
while (jp.nextToken() != JsonToken.END_ARRAY) {
JsonNode node = jp.readValueAsTree();
Log.e("KFF", node.get("col0").asText());
}
} else {
Log.e("KFF", "Error: records should be an array: skipping.");
jp.skipChildren();
}
} else {
Log.e("KFF", "Unprocessed property: " + fieldName);
jp.skipChildren();
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Example of the data i need to parse:
http://pastebin.com/rhD2d9fx

Categories

Resources