How to loop through JSON parameters in android - java

suppose I have a JSON that prints out
{"_id" :"4e3f2c6659f25a0f8400000b",
"confirmation_code":"TWLNX8BT",
"confirmed" :true,
"created_at" :"2011-08-08T00:23:02+00:00",
"email_address" :"dd5dc43ea6bf12ec604b0a7025b94105d419616b",
"first_name" :"sean",
"invites" :[],
"last_name" :"pan",
"raw_email_address":null,
**"tracking_users" :[{
"_id" :"4e407f0659f25a1ce9000007",
"active" :true,
"first_name":"Sean",
"last_name" :"Pan",
"user_id" :"4e3da65e59f25a3956000005"
},{
"_id" :"4e407f7a59f25a1d19000007",
"active" :true,
"first_name":"Sean",
"last_name" :"Pan",
"user_id" :"4e3da65e59f25a3956000005"
},{
"_id" :"4e4085c959f25a204b000004",
"active" :true,
"first_name":"Sean",
"last_name" :"Pan",
"user_id" :"4e3da65e59f25a3956000005"
}],
"updated_at" :"2011-08-08T06:44:31+00:00",
"user_id" :137141}**
in the tracking users part I have three "different" (they're the same for testing purposes) JSON strings within the original JSON. How do I go through the inner parameter (user_id[0]),(user_id[1]),(user_id[2])... of tracking_users in a for loop for android?
I am turning my JSON into a string and then using
obj = new org.json.JSONObject(response) to change it into an object then I use
String trackingusers=obj.getString("tracking_users") to get the three objects in the tracking_users variable.
Thanks

Get tracking_users as JSONArray, then loop them as JSONObject, and with the JSONObject, you can get it's properties, try this:
JSONArray tracking_users = obj.getJSONArray("tracking_users");
for (int i = 0; i < tracking_users.length(); i++) {
JSONObject user = tracking_users.getJSONObject(i);
String _id = user.getString("_id");
and etc..
}

Use getJSONArray("tracking_users") and process each item in the array as an JSONObject.

JSON is composed from Objects and Array of objects. The whole result string is an object. So you loaded it fine. After that, you have to process tracking_users as Array of Objects. So use:
JSONAeeay users = obj.getJSONArray("tracking_users");
and with this, you can cycle through the objects:
int users_count = users.length();
for (int i=0; i<users_count; i++)
{
users.getJSONObject(i)
}

Related

Jackson objectMapper gives different object for same json

I'm passing a json to objectmapper. The JSON string looks like this:
{
"id": "ID1",
"identifier" : "XYZ",
"data": [
{
"id": "sampleParentID",
"childrenElements": [
{
"id" : "sampleChildID",
"content" : "sample child content",
}
]
}
]
}
val objectMapper = ObjectMapper().registerModule(KotlinModule())
val obj: Object1 = objectMapper.readValue(jsonString)
My class looks something like this :
data class Object 1 (
var id : String? = null,
var identifier : String? = null,
var data: MutableList<Element>? = null,
){
// some functions
}
class Element (
var id : String?= null
var content : String? = null
var children: List<Element>? = listOf(),
) {
// som functions
}
From obj, data field is nested which is an object itself.
I want to get hashCode of data so I do obj.data.hashCode(). Let's say 12345 gets generated.
I store this in the database. Now, let's say the user sends another request with exactly the same JSON, again the JSON gets converted into an object from which I extract the data field and now when I do obj.data.hashCode(), 12345 is not generated, rather some other number gets generated.
Is this behavior expected? If yes, what is the workaround?
Update : Added classes description.
Given that your Element class is not a data class (in this case you would get a hashCode() method implementation based on all class properties) you will need to write the hashCode() method yourself so that the default one (based on object memory reference) is not used and you get rid of the behaviour you are currently facing.

Accessing elements in JSON array

I haven't worked much with JSON and I'm using Google Maps Distance Matrix API to get generate some data I'd like to use.
I'd like to pull the number 14147 from duration.
{
"destination_addresses" : [ "Washington, DC, USA" ],
"origin_addresses" : [ "New York, NY, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "226 mi",
"value" : 364089
},
"duration" : {
"text" : "3 hours 56 mins",
"value" : 14147
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I've tried a few different things, here's what I tried last (data is just the array above):
String data = getOutputAsText(geoService);
JSONObject json = new JSONObject(data);
String duration = json.getJSONArray("rows").getString("duration");
Here's the console output:
org.json.JSONException: JSONObject["duration"] not found
I made sure to look around before posting but I haven't found anything that has been able to help me with this particular problem.
I want to pass the value from duration to my own web service, which I can do, I just don't know how to extract the value. Thank you in advance!
First of all, please have a look at this answer. Using org.json you can do smth. like that:
JSONObject obj = new JSONObject("Content of your string here");
JSONArray rows = obj.getJSONArray("rows");
for (int i = 0; i < rows.length(); i++) {
JSONArray elements = rows.getJSONObject(i).getJSONArray("elements");
for(int j = 0; j < elements.length(); j++) {
JSONObject element = elements.getJSONObject(j);
JSONObject duration = element.getJSONObject("duration");
int value = duration.getInt("value");
}
}
The code above has produced following output using your json String: 14147
P.S. You can make use of a library you wish. This one used here was purposed for the demonstrating.

Parse a complex JSON result

I have a json (result) like the below , i need the value of Key "extra", that is "contact office".
I tried the below code, but it did not work, can you help?
JSONArray jsonArray = new JSONArray(result.toString().trim());
JSONObject json = jsonArray.getJSONObject(0).getJSONObject("student").getJSONArray("department").getJSONObject(0).getJSONObject("classes");
String val=json.getString("extra");
// JSON Example
{
"student": [
{
"department" : [
{
"classes" : [
{
"grade" : "A",
"fine" : "No"
},
{
"grade" : "B",
"fine" : "Yes",
"extra" : "contact office"
},
{
"grade" : "C",
"fine" : "NA"
}
],
}
],
}
],
}
You mixed up JSONArray and JSONObject a few times, not sure exactly what I had to change but the following will work:
JSONObject jsonObject = new JSONObject(result.toString().trim());
JSONArray jsonArray = jsonObject
.getJSONArray("student").getJSONObject(0).getJSONArray("department").getJSONObject(0)
.getJSONArray("classes");
String val = jsonArray.getJSONObject(1).getString("extra");
Is this a full sample? If so it doesn't start out as an array. Student is and object not an array. If it is just a sample of one item in the array then you're okay.
The second thing I noticed is: getJSONObject("classes"). Classes is an array not an object, this won't work.
Would you like to consider using JsonPath. You could do something like this -
String[] extraValues = JsonPath.read(json, "$.student[0].department[0].classes[*].extra");

How to parse the Object in JSON type

I have a JSON file and I do not know how can I parse the part of "coordinates", others done already. It seems null, others seem ok when I try to reach them. I guess, coordinates part is another class defined in cities part. Could you please help me to get coordinates of cities?
I kept my cities in a linkedlist.
"cities" : [
{
"code" : "SCL" ,
"name" : "Santiago" ,
"country" : "CL" ,
"continent" : "South America" ,
"timezone" : -4 ,
"coordinates" : {"S" : 33, "W" : 71} ,
"population" : 6000000 ,
"region" : 1
}
static List<City> allCities = new LinkedList<City>();
static List<Flight> allFlights = new LinkedList<Flight>();
static JSONArray cities;
static JSONArray flights;
FileReader reader = new FileReader("csair.json");
JSONObject CSAirData = (JSONObject) JSONValue.parse(reader);
cities = (JSONArray) CSAirData.get("cities");
flights = (JSONArray) CSAirData.get("routes");
Assuming "cities" is an attribute of variable myVar, like this
var myVar = {
"cities": [
{
"code": "SCL",
"name": "Santiago",
...
}
]
};
then you could access "coordinates" by doing
myVar.cities[0].coordinates
"cities" corresponds to an array
the first element in the array (index = 0) is an object
that object has an attribute called "coordinates", which references another object
Edit
Now that I see you are using Java code, you just need to transform this syntax into Java.
We know that "cities" is a JSONArray.
JSONObject city = cities.get(0); // Get the first city in the array (index = 0)
JSONObject coordinates = city.getJSONObject("coordinates");
int coordinates_s = coordinates.getInt("S");
int coordinates_w = coordinates.getInt("W");

How do I read multiple JSON objects in Java?

So this is my sample Json Text,
{
"Date": [
1545,
"20 January 2014"
],
"docText": "ABCD",
"docSource": "",
"docID": 99,
"docDate": "",
"Date": [
1930,
"1995/11",
"past decade",
"today",
"Today"
],
"docText": "JJJJJJJ\"",
"Organization": [
"x",
"y",
"z"
],
"docSource": "",
"docID": 98,
"docDate": "",
"Person": "xxxxxx"
}
Now I need a Java code to Read from this file and Display all the docText, docID Entities. I'm able to retrieve only one Entity.
This is the part of the code im using.
JSONParser jsonParser = new JSONParser();
try {
FileReader fileReader = new FileReader(jsonFilePath);
JSONObject jsonObject = (JSONObject) jsonParser.parse(fileReader);
String docid = (String) jsonObject.get("docText");
System.out.println("DocText: " +docid);
long members = (long) jsonObject.get("docID");
System.out.println("docID: " + members);
JSONArray names = (JSONArray) jsonObject.get("Organization");
Iterator i = names.iterator();
while (i.hasNext()) {
System.out.println("Organization: "+i.next());
I really need this working soon! Thank you
The JSON file has duplicate keys so you probably can't read them all using a standard parser.
From http://www.ietf.org/rfc/rfc4627.txt:
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.
Instead, I'd expect each entity to be a separate object within an array.
AFAIK there is no option to fetch multiple values from a JSON object in a single get...

Categories