I working on NVD3 chart where need to create JSON data for chart as below:
[{
"key" : "North America" ,
"values" : [ [ 1025409600000 , 23.041422681023] , [ 1028088000000 , 19.854291255832] ]
},
{
"key" : "Africa" ,
"values" : [ [ 1025409600000 , 23.041422681023] , [ 1028088000000 , 19.854291255832] ]
},
{
"key" : "South America" ,
"values" : [ [ 1025409600000 , 23.041422681023] , [ 1028088000000 , 19.854291255832] ]
}]
Would somebody please help me create above JSON data using Java as I am trying to create this structure since last 3 hours not successful yet.
Here is the Plunker link: Stacked Area Chart NVD3
Here is the live JSON data example which I want to create in JAVA: JSON example data
Here is solution found by myself:
import org.json.JSONArray;
import org.json.JSONObject;
public class CreateNVD3JSONDataJava {
public static void main(String[] args) {
JSONObject jo = new JSONObject();
jo.put("values", new JSONArray(new Long[][]{{1025409600000L,23L},{1028088000000L,19L},{1030766400000L,21L},{1033358400000L,22L}}));
jo.put("key", "North America");
JSONArray ja = new JSONArray();
ja.put(jo);
ja.put(jo);
ja.put(jo);
System.out.println(ja);
}
}
Edited code:
import org.json.JSONArray;
import org.json.JSONObject;
public class CreateNVD3JSONDataJava {
public static void main(String[] args) {
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
jo.put("values", new JSONArray(new Long[][]{{1025409600000L,23L},{1028088000000L,19L},{1030766400000L,21L},{1033358400000L,22L}}));
jo.put("key", "North America");
ja.put(jo);
jo = new JSONObject();
jo.put("values", new JSONArray(new Long[][]{{1025409600000L,23L},{1028088000000L,19L},{1030766400000L,21L},{1033358400000L,22L}}));
jo.put("key", "Africa");
ja.put(jo);
jo = new JSONObject();
jo.put("values", new JSONArray(new Long[][]{{1025409600000L,23L},{1028088000000L,19L},{1030766400000L,21L},{1033358400000L,22L}}));
jo.put("key", "South America");
ja.put(jo);
System.out.println(ja);
}
}
Output:
[
{
"values": [
[
1025409600000,
23
],
[
1028088000000,
19
],
[
1030766400000,
21
],
[
1033358400000,
22
]
],
"key": "North America"
},
{
"values": [
[
1025409600000,
23
],
[
1028088000000,
19
],
[
1030766400000,
21
],
[
1033358400000,
22
]
],
"key": "Africa"
},
{
"values": [
[
1025409600000,
23
],
[
1028088000000,
19
],
[
1030766400000,
21
],
[
1033358400000,
22
]
],
"key": "South America"
}
]
Related
Need to create a new json file (combined.json) then append multiple json files (json1 and json2) to combined.json.
Example:
Json 1 - previously created json file
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
}
]
Json2 - previously created json file
[
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
Final product:
Combined.json - currenlty created json file
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
Gson gson = new com.google.gson.Gson();
JSONArray combined = gson.fromJson(json1, JSONArray.class);
combined.addAll(gson.fromJson(json2, JSONArray.class));
// verify by looking on the value of: combined.toJSONString()
Very new to JSON. Using json-lib for this and been pulling my hair out trying to get "definitions" from this JSON response by Oxford Dictionaries API. Tried all sorts of things. But can never get anything more specific than everything from "results". Would like to figure out why this is so difficult otherwise will just resort to regex.
JSONObject obj = new JSONObject(stringBuilder.toString());
JSONArray arr = obj.getJSONArray("results");
String test = arr.getJSONObject(1).toString(); // Empty wtf?
String definition = obj.getString("definitions"); // empty also...
Managed to also access "id", "language" and "lexicalEntries" separately, but anything beyond that doesn't seem to want to cooperate.... Is this a normal JSON response? It's quite awkward no? Thanks...
JSON:
{
"metadata": {
"provider": "Oxford University Press"
},
"results": [
{
"id": "ace",
"language": "en",
"lexicalEntries": [
{
"entries": [
{
"homographNumber": "000",
"senses": [
{
"definitions": [
"a playing card with a single spot on it, ranked as the highest card in its suit in most card games"
],
"id": "m_en_gbus0005680.006"
},
{
"definitions": [
"a person who excels at a particular sport or other activity"
],
"id": "m_en_gbus0005680.010",
"subsenses": [
{
"definitions": [
"a pilot who has shot down many enemy aircraft"
],
"id": "m_en_gbus0005680.011"
}
]
},
{
"definitions": [
"(in tennis and similar games) a service that an opponent is unable to return and thus wins a point"
],
"id": "m_en_gbus0005680.013",
"subsenses": [
{
"definitions": [
"a hole in one"
],
"id": "m_en_gbus0005680.014"
}
]
}
]
}
],
"language": "en",
"lexicalCategory": "Noun",
"text": "ace"
},
{
"entries": [
{
"homographNumber": "001",
"senses": [
{
"definitions": [
"very good"
],
"id": "m_en_gbus0005680.016"
}
]
}
],
"language": "en",
"lexicalCategory": "Adjective",
"text": "ace"
},
{
"entries": [
{
"homographNumber": "002",
"senses": [
{
"definitions": [
"(in tennis and similar games) serve an ace against (an opponent)"
],
"id": "m_en_gbus0005680.020",
"subsenses": [
{
"definitions": [
"score an ace on (a hole) or with (a shot)"
],
"id": "m_en_gbus0005680.026"
}
]
},
{
"definitions": [
"achieve high marks in (a test or exam)"
],
"id": "m_en_gbus0005680.028",
"subsenses": [
{
"definitions": [
"outdo someone in a competitive situation"
],
"id": "m_en_gbus0005680.029"
}
]
}
]
}
],
"language": "en",
"lexicalCategory": "Verb",
"text": "ace"
}
],
"type": "headword",
"word": "ace"
}
]
}
String jsonData = sb.toString();
JSONObject obj = new JSONObject(jsonData);
JSONArray resultsArr = obj.getJSONArray("results");
String test = resultsArr.getJSONObject(0).toString();
JSONArray lexicalEntriesArr = resultsArr.getJSONObject(0).getJSONArray("lexicalEntries");
JSONArray entriesArr = lexicalEntriesArr.getJSONObject(0).getJSONArray("entries");
JSONArray sensesArr = entriesArr.getJSONObject(0).getJSONArray("senses");
JSONArray definitionsArr = sensesArr.getJSONObject(0).getJSONArray("definitions");
String definition = definitionsArr.toString();
Reference: http://jsonviewer.stack.hu/
Watch carefully the way we traverse the JSON object and when we should use getJSONObject & getJSONArray methods to retrieve the particular type of data we want from JSON Object.
Update: You might want to iterate the JSON array as per your requirement. I have just explained the case as in how to reach till definitions.
How can I get the value of "distance" out of the following JSON object with java?
{
"destination_addresses" : [ "New York City, New York, Verenigde Staten" ],
"origin_addresses" : [ "Washington D.C., District of Columbia, Verenigde Staten" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "225 mijl",
"value" : 361714
},
"duration" : {
"text" : "3 uur 51 min.",
"value" : 13877
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I tried:
json.getJSONArray("rows").getJSONObject(0).getJSONObject("distance").toString();
But I always get org.json.JSONException: JSONObject["distance"] not found.
I think you are missing the second array "elements", you find array "row" so get object 0, in object 0 you need to find the "elements" array then take the object 0 again, so you can get the "distance" object.
Try this:
json.getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").toString();
Again, I think. I hope this helped you.
Use java-json.jar
Convert JSON String to object and fetch the element.
You can refer this.
Try this:
package Sample;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestMain
{
public static void main(String[] args) throws JSONException
{
String s="{ \"destination_addresses\" : [ \"New York City, New York, Verenigde Staten\" ], \"origin_addresses\" : [ \"Washington D.C., District of Columbia, Verenigde Staten\" ], \"rows\" : [ { \"elements\" : [ { \"distance\" : { \"text\" : \"225 mijl\", \"value\" : 361714 }, \"duration\" : { \"text\" : \"3 uur 51 min.\", \"value\" : 13877 }, \"status\" : \"OK\" } ] } ], \"status\" : \"OK\"} ";
JSONObject jsonObj = new JSONObject(s);
JSONArray array= (JSONArray) jsonObj.get("rows");
JSONObject jsonObj2 =(JSONObject) array.get(0);
JSONArray array2= (JSONArray)jsonObj2.get("elements");
JSONObject jsonObj3 =(JSONObject) array2.get(0);
System.out.println(jsonObj3.get("distance"));
}
}
OUTPUT:
{"text":"225 mijl","value":361714}
I just started using Java and MongoDB. I want to retrieve some data from my database and store it in a list. I want to get a list with only coordinates. (see sample JSON code).
I believe I currently have a list with all the objects in the collection. I only want the coordinates from the data, and store it into a list, I really don't know how to do it.
This is my java code(the connectToMongoCollection method makes (obviously) connection to my database:
DBCollection collection = DBCollections.connectToMongoCollection("collection");
BasicDBList basicDBList = new BasicDBList();
DBCursor cursor = collection.find(new BasicDBObject("type", "feature"));
try {
while(cursor.hasNext()) {
basicDBList.add(cursor.next());
}
} finally {
cursor.close();
}
for(Object object: basicDBList){
BasicDBObject basicDBObject = (BasicDBObject) object;
}
This is the format of a sample MongoDB document.
"features": [
{"type": "Feature",
"properties": { "OBJECTID": 1, "Join_Count": 1, "LABEL": 0 },
"geometry": { "type": "MultiPoint", "coordinates": [ [ 4.3434010517041, 51.891054440280314 ] ] } }
I hope someone can help me, Thanks in advance.
This code will give you coordinates from data stored in a BasicDBList.
public static void main(String[] args) {
try {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("StackOverflow");
DBCollection dbcol = db.getCollection("features");
DBCursor cursor = dbcol.find();
try {
while (cursor.hasNext()) {
DBObject Features = cursor.next();
BasicDBList features = (BasicDBList) Features.get("features");
BasicDBObject[] featuresArr = features.toArray(new BasicDBObject[0]);
for (BasicDBObject dbobj : featuresArr) {
BasicDBObject geometry = (BasicDBObject) dbobj.get("geometry");
BasicDBList coordinates = (BasicDBList) geometry.get("coordinates"); // BasicDBList contains coordinates
System.out.println(coordinates.get(0));
}
}
} finally {
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
This must be your sample mongodb document
{ "features": [
{
"type": "Feature",
"properties": {
"OBJECTID": 1,
"Join_Count": 1,
"LABEL": 0
},
"geometry": {
"type": "MultiPoint",
"coordinates": [
[
4.3434010517041,
51.891054440280314
]
]
}
}
]
}
and output is [ 4.3434010517041 , 51.891054440280314]
I inserted this document in database "StackOverflow" and collection name is "features"
Here's another way to do it. Not necessarily better, but perhaps easier on the person digesting the data.
I am assuming that each doc has a features field that is an array of things including coordinates which can be array of coordinates (not just one). Here are two such docs in collection foo (removed the other fields that aren't important):
db.foo.find().pretty();
{
"_id" : ObjectId("55735cccdbc638d309795958"),
"features" : [
{
"geometry" : {
"type" : "MultiPoint",
"coordinates" : [ [ 1.2, 3.4 ] ]
}
},
{
"geometry" : {
"type" : "MultiPoint",
"coordinates" : [ [ 5.6, 7.8 ] , [ 9.1, 11.12 ] ]
}
}
]
}
{
"_id" : ObjectId("55735cccdbc638d309795959"),
"features" : [
{
"geometry" : {
"type" : "MultiPoint",
"coordinates" : [ [ 83, 94 ] , [ 0.4, 0.5 ] ]
}
},
{
"geometry" : {
"type" : "MultiPoint",
"coordinates" : [ [ 8.3434010517041, 9.891054440280314 ] ]
}
}
]
}
Here's a nice way to use the aggregation framework to unwind all those "arrays within arrays" to give you the 6 coordinate pairs you seek.
db.foo.aggregate([
... {$unwind: "$features"}
... , {$project: { coord: "$features.geometry.coordinates", "_id":0} }
... , {$unwind: "$coord"}
... ]);
{ "coord" : [ 1.2, 3.4 ] }
{ "coord" : [ 5.6, 7.8 ] }
{ "coord" : [ 9.1, 11.12 ] }
{ "coord" : [ 83, 54 ] }
{ "coord" : [ 0.4, 0.5 ] }
{ "coord" : [ 8.3434010517041, 9.891054440280314 ] }
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I want to parse a JSON file in java and get the following values from the file mentioned below:
{
"status": "OK",
"origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
"destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
"rows": [ {
"elements": [ {
"status": "OK",
"duration": {
"value": 340110,
"text": "3 jours 22 heures"
},
"distance": {
"value": 1734542,
"text": "1 735 km"
}
}, {
"status": "OK",
"duration": {
"value": 24487,
"text": "6 heures 48 minutes"
},
"distance": {
"value": 129324,
"text": "129 km"
}
} ]
}, {
"elements": [ {
"status": "OK",
"duration": {
"value": 288834,
"text": "3 jours 8 heures"
},
"distance": {
"value": 1489604,
"text": "1 490 km"
}
}, {
"status": "OK",
"duration": {
"value": 14388,
"text": "4 heures 0 minutes"
},
"distance": {
"value": 135822,
"text": "136 km"
}
} ]
} ]
}
From every element, i want to get the value field of both distance and duration. How do i do this?
Using the json.org reference implementation (org.json homepage, Download here). The code is a bit messy but I think it does what you are asking for. You can take alot of shortcuts by not creating all this objects but to access them directly. The reason that I do it this way is an attempt to make it easier to follow whats happening.
package com.mypackage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"status\": \"OK\",\"origin_addresses\": [ \"Vancouver, BC, Canada\", \"Seattle, État de Washington, États-Unis\" ],\"destination_addresses\": [ \"San Francisco, Californie, États-Unis\", \"Victoria, BC, Canada\" ],\"rows\": [ {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 340110,\"text\": \"3 jours 22 heures\"},\"distance\": {\"value\": 1734542,\"text\": \"1 735 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 24487,\"text\": \"6 heures 48 minutes\"},\"distance\": {\"value\": 129324,\"text\": \"129 km\"}} ]}, {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 288834,\"text\": \"3 jours 8 heures\"},\"distance\": {\"value\": 1489604,\"text\": \"1 490 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 14388,\"text\": \"4 heures 0 minutes\"},\"distance\": {\"value\": 135822,\"text\": \"136 km\"}} ]} ]}";
try {
JSONObject rootObject = new JSONObject(jsonStr); // Parse the JSON to a JSONObject
JSONArray rows = rootObject.getJSONArray("rows"); // Get all JSONArray rows
for(int i=0; i < rows.length(); i++) { // Loop over each each row
JSONObject row = rows.getJSONObject(i); // Get row object
JSONArray elements = row.getJSONArray("elements"); // Get all elements for each row as an array
for(int j=0; j < elements.length(); j++) { // Iterate each element in the elements array
JSONObject element = elements.getJSONObject(j); // Get the element object
JSONObject duration = element.getJSONObject("duration"); // Get duration sub object
JSONObject distance = element.getJSONObject("distance"); // Get distance sub object
System.out.println("Duration: " + duration.getInt("value")); // Print int value
System.out.println("Distance: " + distance.getInt("value")); // Print int value
}
}
} catch (JSONException e) {
// JSON Parsing error
e.printStackTrace();
}
}
}
Create an class structure that reflects the JSON
Use a library like Jackson or GSON to deserialize the json to instances of your classes.
If you want a more dynamic approach, the above frameworks can also serialize to maps.
Use a library for working with JSON. For example google-gson.
as Bozho said create class structure that reflacts JSON and then use jacson library as follow:
refer Parsing JSON File Java
ObjectMapper mapper = new ObjectMapper();
Projects projs =
mapper.readValue(new File("projects.json"),Projects.class);
ArrayList<Project> projects = projs.get("projects");
for (Project p : projects) {
ArrayList<String> description = p.getDescription();
for (String s : description) {
System.out.println(s);
You can use a library like JSON-java
import org.json.JSONObject;
String jsonString = ...
JSONObject object = new JSONObject(jsonString);
String status = object.getString("status");
You can use :
org.bson.Document d = org.bson.Document.parse("{ foo: \"bar\" }");
yes you can use jacson to parse it but there is more easy way to do it
its Jsonme lib "import org.json.me" you dont have to add jar file to use it
JSONObject obj = new JSONObject("{'var1':'val1','var2':200});
String var1=obj.getString("var1");
int var2=obj.getInt("var2");
yes its more easy but if your project is complex i advice you to use jacson lib