Parse Json from Json array in Android - java

I have the following JSON and I would like to parse all of the "vcsapat" and "hcsapat" and all of the datas from the first rows.
Json is here:Link
I tried with the following code, but I only have exceptions
JSONArray JSonAdatok = null;
JSonAdatok = jObject.getJSONArray("vcsapat");
for (int i = 0; i < JSonAdatok.length(); i++) {
JSONObject jo = null;
try {
jo = JSonAdatok.getJSONObject(i);
System.out.print("\n"+jo);
JSONObject kezdojatekosok = jo.getJSONObject("kezdo");
System.out.print("\n"+kezdojatekosok);
for (int j = 0; j < kezdojatekosok.length(); j++) {
JSONObject egyjjson = kezdojatekosok;
And the Exception is the following:
at org.json.JSON.typeMismatch(JSON.java:100)
org.json.JSONObject.getJSONArray(JSONObject.java:588)

Your JSON contains first an Object which starts with "{" so your whole JSON string represents an JSONObject. Then after, get inside it the object "hforma" then the JSONArray of forma, and then you can iterate on them to get on each the hcsapat and vcsapat attributes as strings.
Something like this:
JSONObject complete = new JSONObject(WHOLE_JSON_AS_STRING);
JSONObject hforma = complete.getJSONObject("hforma");
JSONArray forma = hforma.getJSONArray("forma");
for (int i = 0; i < forma.length(); i++) {
JSONObject formaData = forma.getJSONObject(i);
String hcsapat = formaData.getString("hcsapat");
String vcsapat = formaData.getString("vcsapat");
}
I did not test that code, it is just an example that follows the structure of your JSON.

Related

How to parse array into array JSON

first of all I wanted to know if the structure of the json is correct, you can find the JSON here:
http://demo8461125.mockable.io/whitemage
if it is correct I would like to know how to parse "PANINI" , is an array inside an array "tipopietanza"
JSONArray arr = response.getJSONArray("pietanze");
for (int i = 0; i < arr.length(); i++)
{
JSONArray pietanze = response.getJSONArray("PANINI");
List<Pietanze> listapietanze =new ArrayList<>(pietanze.length());
for(int j=0;j<pietanze.length();j++)
{
Pietanze tmp = new Pietanze();
tmp.setNome(pietanze.getJSONObject(j).getString("nomepietanza"));
listapietanze.add(tmp);
}
expandableListDetail.put(arr.getJSONObject(i).getString("tipopietanza"), listapietanze);
}
Yes, it should work, but I suggest just use Gson:
Type type = new TypeToken<List<TipiPaniniAndServizi>>(){}.getType();
List<TipiPaniniAndServizi> tipiPaniniAndServizi = gson.fromJson(json, type);
And save your time from manipulate JSON, just think about your java objects.
JSON structure is okay.
You need to do minor changes in your code for getting list properly.
JSONArray arr = response.getJSONArray("pietanze");
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
if(jsonObject.has("PANINI")) {
JSONArray paniniJsonArray = jsonObject.getJSONArray("PANINI");
List<Panini> listPanini = new ArrayList<>();
for (int j = 0; j < paniniJsonArray.length(); j++) {
Panini panini = new Panini();
panini.setId(paniniJsonArray.getJSONObject(j).getString("id"));
panini.setNomepietanza(paniniJsonArray.getJSONObject(j).getString("nomepietanza"));
panini.setPrezzo(paniniJsonArray.getJSONObject(j).getString("prezzo"));
listPanini.add(panini);
}
expandableListDetail.put(arr.getJSONObject(i).getString("tipopietanza"), listPanini);
}
}

parsing json object to android string

I have tried to parse a JSON object by lot of ways but can't figure out how to parse that.
This is my json string:
{
"JSONDataResult":
{"Messages":
[{ "Id":"0",
"Category":"Sport",
"Title":"It's a goal",
"Content":"sport content"
}]
}
}
I tried this:
JSONArray arr = result.getJSONArray("Messages\\");
for (int j = 0; i < arr.length(); j++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
Id = result.getString("Id\\");
Title = result.getString("Title\\");
Content = result.getString("Content\\");
}
there must be a lot of answers out there but this is the one i did.
guess we have a String coming from server or getting it from android cache where you stored before..
String listdata = "some kind of json data, might be your sample..";
JSONObject jsnobject = new JSONObject(listdata);
System.out.println("jsnobject: " + jsnobject);
return jsnobject.getJSONArray("Messages");
or you already have the reponse as a list structured
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
.....
}
First you convert it to a valid json object that a json array. where you want the list starts, Messages etc.. so that you can get each elements id, title ..
by getString in you example..
grats
Slash is not required. You simply do this
JSONArray arr = result.getJSONArray("Messages");
for (int j = 0; i < arr.length(); j++)
{
JsonObject object = arr.getJSONObject(i);
Strng id = object .optString("Id");
String Title = object .optString("Title");
}

Read specific items from JSON http request

I get JSON from a rest server (jax rs) through a http request.
[{"carId":"t0","movements":[{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":8,"lane":{"laneId":"--104_0"},"position":73.76,"speed":14.49,"timeStep":8.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":16,"lane":{"laneId":"--104_0"},"position":89.35,"speed":15.59,"timeStep":9.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":27,"lane":{"laneId":"--104_0"},"position":106.39,"speed":17.03,"timeStep":10.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":{"latitude":"51.404057790546894","longitude":"5.424575687577547","nodeId":"-14"}},"id":35,"lane":{"laneId":"--104_0"},"position":125.24,"speed":18.85,"timeStep":11.0},{"edge":{"edgeId":"--104","fromNode":{"latitude":"51.404456094285734","longitude":"5.477570348298111","nodeId":"-16"},"lanes":[{"laneId":"--104_0"},{"laneId":"--104_1"}],"toNode":
Just to give you an idea how the JSON looks like.
Now I want to convert every item of this JSON file to an Java object.
So I want to see inside the "fromNode" to get the attributes to make an object.
I can see all the movement and edges, thats no problem (i do that like this):
String jsonStringMike = callURL("http://----------/");
try {
JSONArray jsonArrayMike = new JSONArray(jsonStringMike);
int countMike = jsonArrayMike.length(); // get totalCount of all jsonObjects
for (int i = 0; i < countMike; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArrayMike.getJSONObject(i); // get jsonObject # i position
JSONArray movement = jsonObject.getJSONArray("movements");
String edge = movement.getJSONObject(i).getString("edge");
System.out.println(edge);
So this provides me with all the "edge's" From the JSON file shown before. But if I want to see the "fromNode" I get the following error:
org.json.JSONException: JSONObject["edge"] is not a JSONArray.
This is the code that is not working and will provide the given error.
public static void main(String[] args) throws IOException, JSONException {
String jsonStringMike = callURL("http://6--------------");
try {
JSONArray jsonArrayMike = new JSONArray(jsonStringMike);
int countMike = jsonArrayMike.length(); // get totalCount of all jsonObjects
for (int i = 0; i < countMike; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArrayMike.getJSONObject(i); // get jsonObject # i position
JSONArray movement = jsonObject.getJSONArray("movements");
int o = movement.length();
String test = movement.toString();
JSONArray jsonArray2 = new JSONArray(test);
for (int p = 0; p < o; o++) {
JSONObject moveObject = jsonArray2.getJSONObject(p);
JSONArray edge = moveObject.getJSONArray("edge");
String fromNode = edge.getJSONObject(p).getString("fromNode");
System.out.println(fromNode);
}
Does anybody knows how I can look "deeper" into the given JSON file?
I think you are almost there, the issue in your code that in the loop moveObject is your edge json object, so movemen.length() is the the count of all edge json objects in the array. I have not tested this, but I think it should work. Also, your for loop has typo, o++ should be p++,
JSONArray jsonArrayMike = new JSONArray(jsonStringMike);
int countMike = jsonArrayMike.length(); // get totalCount of all jsonObjects
for (int i = 0; i < countMike; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArrayMike.getJSONObject(i); // get jsonObject # i position
JSONArray movement = jsonObject.getJSONArray("movements");
int o = movement.length();
for (int p = 0; p < o; p++)
{
JSONObject movementObject = movement.getJSONObject(p);
JSONObject edgeObject = movementObject.getJSONObject("edge");
JSONObject fromNode = edgeObject.getJSONObject("fromNode");
String latitude = fromNode.getString("latitude");
String longitude = fromNode.getString("longitude");
String nodeId = fromNode.getString("nodeId");
System.out.println(fromNode);
}
}

new to json parsing - how to get an array within an array

from the following link , I need to get the value stored in "media".
Here is my code:
Content = Content.replace("jsonFlickrFeed(", "");
Content = Content.replace("})", "}");
jsonResponse = new JSONObject(Content);
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
But I can not access past "items"
You will have to loop through the JSON like this:
...
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");
for (int i=0; i<jsonMainNode.length(); i++) {
String media = jsonMainNode.getJSONObject(i).getString("media");
}
This will loop through the images and return the value(s) in media.
In your case it should be something like this:
..
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");
for (int i=0; i<jsonMainNode.length(); i++) {
JSONObject finalNode = jsonMainNode.getJSONObject(i);
JSONArray finalArray = finalNode.optJSONArray("media");
for (int j=0; j<finalArray.length(); j++) {
String m = finalArray.getJSONObject(j).getString("m");
}
}
...because there is another node inside the media node, called m.
Here is an example getting the tags string for each item in the JSONArray that you have:
for (int i = 0; i < jsonMainNode.length(); i++){
JSONObject jsonObject = jsonMainNode.getJSONObject(i);
String tags = jsonObject.getString("tags");
}
This will iterate through all JSONObjects that are in the array, and extract the tags field from each object.
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject item = (JSONObject) jsonMainNode.get(i);
JSONObject media = item.getJSONObject("media");
String valueMedia = media.getString("m");
Log.d("TAG", valueMedia);
}

Processing a JSON string into a Java Array

I have this array in json code.
$info=array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
array_push($info,$row);
}
$info;
$result_final->lugares_cercanos = $info;
Print this:
{"logstatus":"1","lugares_cercanos":[{"nombre":"Rio Amazonas","distancia":"5119.000"}{"nombre":"Swissotel Quito","distancia":"5823.000"}{"nombre":"Laguna de Yaguarcocha","distancia":"71797.000"}]}
Now, the problem is, How can I put the fields of "lugares_cercanos" into java ArrayList??
I try with this code:
{
JSONArray jdata=post.getserverdata(postparameters2send, URL_connect);
if (jdata!=null && jdata.length() > 0){
JSONObject json_data;
ArrayList<NameValuePair> lugares = new ArrayList<NameValuePair>();
json_data = jdata.getJSONObject(0);
logstatus=json_data.getInt("logstatus");
lugaresCercanos=json_data.getJSONArray("lugares_cercanos");
for (int i = 0; i < lugaresCercanos.length(); ++i) {
JSONObject rec = lugaresCercanos.getJSONObject(i);
String name = rec.getString("nombre");
String dist = rec.getString("distancia");
lugares.add(new BasicNameValuePair(name,dist));
}
}
}
Try this:
JSONObject j = jdata.getJSONObject("obj");
JSONArray jArray = j.getJSONArray("lugares_cercanos");
int len = jArray .length();
for(int i=0; i <len; i++){
String nombre = jArray .getJSONObject(i).optString("nombre");
---------
}
The top level structure (i.e. the JSON string you have posted) is not an array but an object.
I don't know what your post.getserverdata method does, if there is a version that can return a JSONObject you could use:
JSONObject jdata=post.getserverdataobject(postparameters2send, URL_connect);
logstatus=jdata.getInt("logstatus");
lugaresCercanos=jdata.getJSONArray("lugares_cercanos");
...
show this error:
Error parsing data org.json.JSONException: Value {"lugares_cercanos":[{"nombre":"Laguna de Yaguarcocha","distancia":"8686205.000"},{"nombre":"Swissotel Quito","distancia":"8728811.000"},{"nombre":"Rio Amazonas","distancia":"8729333.000"}],"logstatus":"1"} of type org.json.JSONObject cannot be converted to JSONArray

Categories

Resources