Parse JSONObject and JSONArray and fix them in the listview - java

How to parse JSONArray inside JSONObject?. Here is the JSON response I'm getting from the server.
{
"searchdata": {
"titles": [
"<b>Laptop</b> - Wikipedia, the free encyclopedia",
"<b>laptop</b> - definition of <b>laptop</b> by the Free Online Dictionary ..."
],
"desc": [
"A <b>laptop</b> computer is a personal computer for mobile use. A <b>laptop</b> has most of the same components as a desktop computer, including a display, a keyboard, a ...",
"lap·top (l p t p) n. A portable computer small enough to use on one&apos;s lap. <b>laptop</b> [ˈlæpˌtɒp], <b>laptop</b> computer. n (Electronics & Computer Science / Computer ..."
],
"links": [
"http://en.wikipedia.org/wiki/Laptop",
"http://www.thefreedictionary.com/laptop"
],
"nextpage": ""
}
}
I'm able to get JSONObject but how to get JSONArray one by one, so that I can fix them in the listview.
I want to show the values of each array in a single row of the listview and so on....
Any help will be appreciated.

Very easy..
you need to fix code like this:
//jsonString is your whole JSONString which you have shown above
JSONObject jObj = new JSONObject(jsonString);
JSONObject jSearchData = jObj.getJSONObject("searchdata");
JSONArray jTitles = jSearchData.getJSONArray("titles");
JSONArray jDesc= jSearchData.getJSONArray("desc");
JSONArray jLinks= jSearchData.getJSONArray("links");
String nextPage = jSearchData.getString("nextpage");
//and so on and so forth
For fetching the array items and show it into a listview:
//you can iterate over each item and add it to an ArrayList like this:
//i am showing you a single one,follow the same process for other arrays:
ArrayList titlesArray = new ArrayList();
for (int i = 0; i < jTitles.length(); i++) {
String item = jTitles.getString(i);
titlesArray.add(item);
}
Next you make this arraylist a source to a listview like this:
// Get a handle to the list view
ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setAdapter(new ArrayAdapter<string>((Your activity class).this,
android.R.layout.simple_list_item_1, titlesArray));

Consider that your top level JSON will be parsed into a JSONObject, and that subsequently you can request to receive from it, any sub level objects and/or arrays via the methods getJSONObject(name) and getJSONArray(name). Your arrays of interest are two levels deep in the JSON hierarchy, so you will need something like this:
String json = ...;
JSONObject rootObj = new JSONObject(json);
JSONObject searchObj = rootObj.getJSONObject("searchdata");
JSONArray titlesObj = searchObj.getJSONArray("titles");
JSONArray descsObj = searchObj.getJSONArray("desc");
JSONArray linksObj = searchObj.getJSONArray("links");
You can iterate any of the arrays as such (using titles as an example):
for(int i = 0; i < titlesObj.length(); i++) {
String title = titlesObj.getString(i);
}

it will be help:
JSONArray titles = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("titles");
JSONArray desc = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("desc");
JSONArray links = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("links");

Related

How to access JSON value?

Very new to JSON, this is probably very simple but I'm not sure how to access the "coordinates" in this JSON I know how to go from resourceSets to resources but get stuck at "point":
{
"resourceSets":[
{
"estimatedTotal":1,
"resources":[
{
"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox":[
51.3223903,
-0.2634519,
51.3246386,
-0.2598541
],
"name":"name",
"point":{
"type":"Point",
"coordinates":[
51.3235145,
-0.261653
]
}
}
]
}
]
}
My code so far:
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject)parser.parse(result);
JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");
for (int i = 0; i < jsonArray.size(); i ++) {
JSONObject jObjResourceSets = (JSONObject)jsonArray.get(i);
JSONArray jsonArray2 = (JSONArray)jObjResourceSets.get("resources");
System.out.println("Coords" + jObjResourceSets.get("point"));
}
Lets analyse what you're doing (and need to be doing), step by step, in order to get the "coordinates".
First of all, JSON is a great language to transfer static data. It works like a dictionary, where you have a key and the respective value. The key should always be a String, but the value can be a String, an int/double or even an array of other JSON objects. That's what you have.
For instance, "estimatedTotal" is an element (JSONObject) from the "resourceSet" array (JSONArray).
JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");
What you're saying here is straight forward: from your overall JSONObject - jObj - you want to extract the array with key "resourceSets".
Now you have direct access to "resourceSets" array elements: "estimatedTotal", "resources", etc. So, by applying the same logic, in order to access "coordinates" we need to access the "resources" array. And by that I mean to create a JSONArray object like we did before.
JSONArray jsonResourcesArray = (JSONArray)jObjResourceSets.get("resources");
I hope it's clear what's the content of jsonResourcesArray here. It's the JSON array of "__type", "bbox", "name", "point", (...). The Coordinates howevere are inside "point" JSON object. How do we access it?
JSONObject jsonPointObject = (JSONObject) jsonResourcesArray.get("point");
And you know by know that "jsonPointObject" has as its values the following JSON objects: "type" and "coordinates". Coordinates is an array of values, so do we have to use JSONArray or JSONObject?
JSONArray jsonCoordinatesArray = (JSONArray) jsonPointObject.get("coordinates");
From which we mean: from the jsonPointObject we want to extract the array that has key "coordinates". Now your array is a JSONArray with values of jsonCoordinatesArray.get(0) and jsonCoordinatesArray.get(0).
Now you have, not only the code to get those values, but the understanding of how JSON works and how Java interacts with it so you can solve any Json problem from now on.
Normally this code works for the given JSON object. However I'll put the tested formatted JSON value below the java code so you can test it as well.
Note that this code will get you all the coordinates of all the elements in your object.
public static void main(String[] args) throws Exception {
String result = getJsonString();
// Getting root object
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject)parser.parse(result);
// Getting resourceSets Array
JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");
for (int i = 0; i < jsonArray.size(); i++) {
// Getting the i object of resourceSet
JSONObject jObjResourceSets = (JSONObject) jsonArray.get(i);
// Getting resources list of the current element
JSONArray jsonArray2 = (JSONArray) jObjResourceSets.get("resources");
for (int j = 0; j < jsonArray2.size(); j++) {
// Getting the j resource of the resources array
JSONObject resource = (JSONObject) jsonArray2.get(j);
// Getting the point object of the current resource
JSONObject point = (JSONObject) resource.get("point");
// Getting the coordinates list of the point
JSONArray coordinates = (JSONArray) point.get("coordinates");
for (int k = 0; k < coordinates.size(); k++) {
System.out.println("Coordinates[" + k + "]: " + coordinates.get(k));
}
// Printing an empty line between each object's coordinates
System.out.println();
}
}
}
The tested JSON Object:
{
"resourceSets":[
{
"estimatedTotal":1,
"resources":[
{
"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox":[
51.3223903,
-0.2634519,
51.3246386,
-0.2598541
],
"name":"name",
"point":{
"type":"Point",
"coordinates":[
51.3235145,
-0.261653
]
}
}
]
}
]
}
If it worked please mark it as the answer.
Good luck ^^
B.
You need the following piece of code to get the data.
JSONArray jsonArray2 = (JSONArray)jObjResourceSets.get("resources");
/**
* here we should note that the "resources" is only having one JSON object hence we can take it as below
* from 0th index using ((JSONObject)jsonArray2.get(0)) these piece of code and the next part is to take the point JSONObject
* from the object.
*/
JSONObject temp = (JSONObject)((JSONObject)jsonArray2.get(0)).get("point");
System.out.println("Coords"+temp.get("coordinates")); //this will give you the coordinates array
//now if you want to do further processing, traverse in the jsonArray like below
JSONArray arr= (JSONArray)temp.get("coordinates");
System.out.println("X coordinate:"+arr.get(0));
System.out.println("Y coordinate:"+arr.get(1));
For more information and further details on JSONObject and JSONArray you can go through this linkparsing-jsonarray-and-jsonobject-in-java-using-json-simple-jar
json-simple-example-read-and-write-json

How to put an value to the extracting JSON and display it

I wanna display a parsed json with my values . I mean , I wanna add some values to the json and display it . I can display all result from respond , but I wanna display just the json with my values not all data :)
here i have parsed allready my json
JSONObject jsonObject = new JSONObject(adresUrl);
JSONArray offerResources = jsonObject.getJSONArray("offerResources");
for(int y = 0; y < offerResources.length(); y++){
JSONObject currentTransfer = offerResources.getJSONObject(y);
JSONArray meetPoint = currentTransfer.getJSONArray("meetPoints");
for (int i = 0; i < meetPoint.length(); i++){
JSONObject currentMeetPoints = meetPoint.getJSONObject(i);
String startAddress = currentMeetPoints.getString("startAddress"); // here i wanna put some values , but i dont know how
// here is a litle piece of my json :)
"meetPoints": [
{
"startAddress": "....", // after the collon i have to put my value .
"startLocation": {
thank you for your help
I'm not sure if I understood your question fully but from what I got here is some solution. I simply created a string and couple of Json objects and jsonarray for adding the list of values and put it inside the main json object "jsonValueObject " and accumulate it inside meetPoints.
Accumulate(String key,Object Value) is a key value pair, meaning if key is created then Object is checked for being an array,and if this array has "values", it will be added else new array will be created. "Put" will replace the value if the key exists.
String jsonString = "{\"results\":[{\"Country\":\"value\",\"state\":\"value\" },
{ \"Country\":\"value\", \"state\":\"value\"}]}";
JSONObject meetPoints = new JSONObject(jsonDataString);
JSONObject jsonValueObject = new JSONObject();
JSONArray list = new JSONArray();
jsonValueObject.put("Country", "newValue");
jsonValueObject.put("state", "newValue");
jsonValueObject.put("city", "Chennai");
jsonValueObject.put("street", "Bharathiyar Street");
jsonValueObject.put("date", "14May2017");
jsonValueObject.put("time", "10:00AM");
list.put(jsonValueObject);
meetPoints.accumulate("values", list);
System.out.println(meetPoints);

Library to create JSON file from parsed text document

I parsed a timetable from a text document and reached the step where I have to create a JSON file from the raw data like in the sample below. Is there any library which could help me create a JSON formatted file from a raw text document?
I appreciate any help.
Sample how it could look like:
{"route": 1
"info": [
{"direction": "Surrey Quays"},
{"stops": [{"stops_name": "Lancaster Place"},
{"arrival_time":{
"mon-fri": ["04:41", "05:41", "06:09"],
"sat": [ "05:38", "06:07","06:37"]
}
}
]
}
Some sample from the text document
Surrey Quays
1
Lancaster Place
mon-fri 04:41 05:41 06:09
sat 04:41 05:41 06:09
Edit:
for (Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
List<String> timeEntries = entry.getValue();
JSONObject timeTable = new JSONObject();
timeTable.put("route", route);
JSONObject info = new JSONObject();
info.put("direction", direction);
JSONObject stops = new JSONObject();
stops.put("stops_name", key);
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
JSONArray someArray = new JSONArray(timeEntries);
arrivalMoFr.put( someArray);
arrivals.put("mon-fri", arrivalMoFr);
stops.put("arrival_time", arrivals);
info.put("stops", stops);
timeTable.put("info", info);
System.out.println(timeTable.toString(3));
}
**Some of the result **
"arrival_time": {"mon-fri": [[
"05:04",
"05:39",
"19:11",
"19:41",
"20:11"
]]},
You could use this JSON library from json.org . But it is just one example of all the libraries out there.
This is how you could use it:
Let's say you already have your parser (meaning you already have a method that can read the text document and that knows what to do with the data)
JSONObject timeTable = new JSONObject(); // first create the "main" JSON Object
timeTable.put("route", 1); // this first entry is just a number
JSONObject info = new JSONObject(); // now you need a second JSON OBject to put all the info in
info.put("direction", "Surrey Quays"); // first info, the direction
JSONObject stops = new JSONObject(); // now you need another Object for all the stops and stop related info
stops.put("stops_name", "Tension Way"); // like the name for the stop
JSONObject arrivals = new JSONObject(); // now all the arrivals
JSONArray arrivalMoFr = new JSONArray(); // this is the first time where an array makes sense here
arrivalMoFr.put("05:38"); // arrival time 1
arrivalMoFr.put("06:07"); // arrival time 2
arrivalMoFr.put("06:37"); // ...
arrivals.put("mon-fri",arrivalMoFr); // add the arrival times array as mon-fri to the arraivals object, do the same with all other arrival times (Saturday, Sunday...)
stops.put("arrival_time", arrivals); // now add the arrival time object to your stops
info.put("stops", stops); // and put the stops to your info
timeTable.put("info", info); // once you added all your infos you can put the info into your timeTable
System.out.println(timeTable.toString(3)); // this is just for testing. The number 3 tells you how many whitespaces you want for text-identaion
And this is the output I am getting:
{
"route": 1,
"info": {
"stops": {
"arrival_time": {"mon-fri": [
"05:38",
"06:07",
"06:37"
]},
"stops_name": "Tension Way"
},
"direction": "Surrey Quays"
}
}
I realize this is not exactly the same as in your example. But I think you get the idea. Remember, the order of the elements in a JSON Object is irrelevant. When reading the JSON, the program will read it like json.get("stops_name"); and it does not care if the stops name are before or after the arrival times.
ADDITION
I saw that you put the "stops_name" and the "arrival_time"-array in separate JSON Objects. Well if you want to put them all in an object called "stops", which suggests, that you will list more than one stop, I suggest to put them together. Because the data in the JSON object has no particular order.
"stops": [
{
"stop_name" : "Lanvester Place",
"arrival" : {...}
},{
"stop_name" : "Some other Place",
"arrival" : {...}
}
...
]
To your EDIT:
your are getting double braces [[ because you are adding an array to your arrivals Object where the first entry is again an array.
so instead of doing this:
JSONArray arrivalMoFr = new JSONArray();
JSONArray someArray = new JSONArray(timeEntries);
arrivalMoFr.put( someArray);
arrivals.put("mon-fri", arrivalMoFr);
you should do this:
JSONArray arrivalMoFr = new JSONArray(timeEntries); // put your list of time entries directly into the arrivalMoFr array
arrivals.put("mon-fri", arrivalMoFr); // then add the arrivalMoFr array to the arrivals object
You need to parse the text file first. I sugest to create dedicated Java classes for your data. Make sure the classes reflect the structure of the desired JSON.
Once you have that you can feed youf Java object to a JSON library which turns it into JSON for free. I'm using GSON for that. I'm sure you will find some more candidates on SO or Google.

I am getting a type error when looping JSONArray in Android / Java

I want to access posters and loop it in this JSON sting.
{"r":
{"posters":
[
{"rev":10,"poster_id":4,"poster_filename":"545397373c2c7","poster_filepath":"\/poster_files\/545397373c2c7","poster_synopsis":"This is the new synopsis for this exquisite poster I have created. You will marvel at its greatness and ask many questions.","poster_title":"Poster A"},
{"rev":6,"poster_id":7,"poster_filename":"5453b54b83b5f","poster_filepath":"\/poster_files\/5453b54b83b5f","poster_synopsis":"This is a synopsis that is not real. No one can say what this synopsis really means. It is total B.S..","poster_title":"Poster A"}
],
"msg":"72 & 2",
"status":"complete"}
}
I have this to convert the string to JSONObject:
JSONObject jsonObject = new JSONObject(result);
JSONObject r = new JSONObject(jsonObject.getString("r"));
JSONArray posters = r.getJSONArray("posters");
Android Studio says "Array type expected, found org.json.JSONArray when I try to loop posters:
int arraySize = posters.length();
TextView myTextView = (TextView) findViewById(R.id.show_download_list);
for(int i = 0; i < arraySize; i++) {
myTextView.append(posters[i]);
myTextView.append("\n");
}
Am I not converting the object correctly??
JSONObject jsonObject = new JSONObject(result);
JSONObject r = jsonObject.getJSONObject("r");
JSONArray posters = r.getJSONArray("posters");
I changed the r JSONObject to get it from the JSONObject called r instead of calling string called r ,, because r in the json string is an object
Update
Change first line in the loop to be myTextView.append(posters.getJSONObject(i).getString("poster_title")); , this will print the poster title on each text view.
the problem here is that you are dealing with the JSON array as an ordinary array.

simpleJson parsing in Java

I'm very new to parsing JSON. I have looked all over and cannot seem to grasp the idea to my particular problem. I'm having a hard time understanding how to get a JSON object from a JSON array. My example is below
[{"styleId":94,
"status":"verified",
"abv":"4.2",
"name":"Bud Light"}]
Here is my current code
JSONParser parser = new JSONParser();
Object obj = parser.parse(inputLine);
JSONObject jsonObject = (JSONObject) obj;
Long currPage = (Long)jsonObject.get("currentPage");
System.out.println(currPage);
JSONArray jArray = (JSONArray)jsonObject.get("data");
System.out.println(jArray);
inputLine is my orignal JSON. I have pulled a JSONArray out of the original JSONObject that has the "data" tag. Now this is where I'm stuck and given the JSONArray at the top. Not sure how to iterate through the Array to grab JUST the "name" tag.
Thanks for the help in advanced!
To iterate in a JSONArray you need to go through each element in a loop.
int resultSize = jArray.length();
JSONObject result;
for (int i = 0; i < resultSize; i++) {
result = resultsArray.getJSONObject(i);
String name = result.getString("name");
// do whatever you want to do now...
}
just use Gson . it works well out of the box with any object type you supply.
This is an example from the user's guide:
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);

Categories

Resources