How to Parameterize jsonSurfer collectOne method - Java/Json Parsing - java

Let's say I have a file sample.json
{"Students":
[
{"Name": "ABC", "id" = "one"},
{"Name": "XYZ", "id" = "two"}
]
}
How do I retrieve an array element object by passing its index number as an argument ?
For example, I want to get array element with variable name ABC. So indexNum is 0 in this case.
I tried below but it doesn't work.
InputStreamReader reader = read("sample.json");
Object obj = jsonSurfer.collectOne(reader,"$.Students[indexNum]");
Not sure if JsonSurfer supports parametrizarion. Any suggestions please. Thanks.

Following code should work:
int indexNum = 0;
String jsonPath = "$.Students["+indexNum+"]";
Object obj = jsonSurfer.collectOne(reader,jsonPath);

Related

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.

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

Converting Nested Json files to CSV in java

{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
This is how my Json file looks .I m required to convert this json to a csv .(I m trying to convert a multi-dimesional data to 2d).I m using gson for my purpose.I cannot use gson.fromgson() function to object map with a template because it should be generic .
I know we can use CDL to convert jsonarray to csv format but It wont work in my case .
my csv format looks like
Employee*
empMID,comment.$,contact.address,contact.freetext,gender
mock:1,,2400 waterview,TRUE,male
mock:123,,2200 waterview,TRUE,female
colA#
TRUE
colB#
FALSE
I tried using google-GSON api to convert to this format .But I m not able to convert to this format .I have used * to represent its a json array and # to represent its a primitive type and contact.address to represent nested array inside another json array .I having problem relating this nested structure .I m able to traverse everything recursively like a column. Thanks in advance
public static void main(String[] args) throws IOException{
BufferedReader reader=null;
StringBuilder content=null;
String result=null;
reader = new BufferedReader(new FileReader("temp.json"));
String line = null;
content= new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
result= content.toString();
JsonElement jelement = new JsonParser().parse(result);
printJsonRecursive(jelement);
}
public static void printJsonRecursive(JsonElement jelement){
if(jelement.isJsonPrimitive()){
System.out.println(jelement.getAsString());
return;
}
if(jelement.isJsonArray()){
JsonArray jarray= jelement.getAsJsonArray();
for(int i=0;i<jarray.size();i++){
JsonElement element= jarray.get(i);
printJsonRecursive(element);
}
return;
}
JsonObject jobject= jelement.getAsJsonObject();
Set<Entry<String, JsonElement>> set= jobject.entrySet();
for (Entry<String, JsonElement> s : set) {
printJsonRecursive(s.getValue());
}
}
}
You can achieve this thru reflection if you have a object mapped to the json.
use gson/jackson to convert json to java object
append fields using reflection by iterating the class and get any field you interested in.
append value with reflection by getting value from the target object.
More detail look at my blog post below:
vcfvct.wordpress.com/2015/06/30/converting-nested-json-files-to-csv-in-java-with-reflection/
You are not printing the key. This should fix it.
for (Entry<String, JsonElement> s : set) {
System.out.println(s.getKey()); //Added
printJsonRecursive(s.getValue());
}
You can take care of \ns from here.
EDIT
If you want to print the keys just once for repeating json objects, create a Java bean to hold the data and populate it during your recursion. Once the bean is complete, add a method there to print all the data in the format you want (printing keys only once and so on).
You can use the library json2flat for converting your JSON to CSV.
This library doesn't require any POJO's. It simply takes your JSON as string and returns a 2D representation of it in the format of List<Object[]>.
For example for the JSON:
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
It gives an output:
/cola,/colb,/Employee/empMID,/Employee/col1,/Employee/gender,/Employee/contact/address,/Employee/contact/freetext
,,"mock:1","something",,"2400 waterview",true
,,"mock:2","something",,"2200 waterview",true
false,false,,,,,
/**
* Get separated comlumns used a separator (comma, semi column, tab).
*
* #param headers The CSV headers
* #param map Map of key-value pairs contains the header and the value
*
* #return a string composed of columns separated by a specific separator.
*/
private static String getSeperatedColumns(Set<String> headers, Map<String, String> map, String separator) {
List<String> items = new ArrayList<String>();
for (String header : headers) {
String value = map.get(header) == null ? "" : map.get(header).replaceAll("[\\,\\;\\r\\n\\t\\s]+", " ");
items.add(value);
}
return StringUtils.join(items.toArray(), separator);
}

Parsing JSON data in Java for Android

I hope someone might be able to help me.
I am trying to parse following json file:
{"seminar":[
{"categoryid": "1","cpe": "13","inventory":["Discussion","Value x","Value y"
],"teachers": [
{
"titel": "Dipl.-Ing.",
"company": "XY",
"name": "Test",
"id": "3",
}
],
},...
I am lost with parsing the teachers data in...
...
private static final String TAG_teachers = "teachers";
private static final String TAG_TITLE = "title";
for(int i = 0; i < seminar.length(); i++){
JSONObject c = seminar.getJSONObject(i);
...
teachers = c.getJSONArray(TAG_DOZENTEN);
for(int z = 0; z < teachers.length(); z++){
JSONObject d = teachers.getJSONObject(z);
String title = d.getString(TAG_TITLE);
Log.d("JSONParsingActivity", title);
I get the error System.err(1010): org.json.JSONException: Value null
at teachers of type org.json.JSONObject$1 cannot be converted to
JSONArray.
What did I do wrong? As I understand from the JSON documentation, teachers is an JSON Array and not an Object. Is somebody able to help me?
You have an extra (trailing) comma in teachers (after "3"). Not allowed in JSON. Remove it and see if that helps.
If your JSON is really of the form:
{ ... }, { ... }, { ... }, ...
This is invalid JSON
The root enclosure must either be a single object (in {}) or an array (in []).
If your intent is to send an array of objects, then simply wrap the entire thing with square brackets to make it an array and create a JSONArray object from it.
So it must be like this
[ { ... }, { ... }, { ... }, ... ]
You also need to make sure that you don;t have extra commas, unclosed brackets, etc. Use JSONLint or other similar JSON format checker to save yourself some time in finding syntax problems.

How to loop through JSON parameters in android

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

Categories