I have Java app that takes data from external app. Incoming JSONs are in Strings. I would like to parse that Strings and create BSON objects.
Unfortunate I can't find API for that in Java's BSON implementation.
Do I have use external parser for that like GSON?
... And, since 3.0.0, you can:
import org.bson.Document;
final Document doc = new Document("myKey", "myValue");
final String jsonString = doc.toJson();
final Document doc = Document.parse(jsonString);
Official docs:
Document.parse(String)
Document.toJson()
Official MongoDB Java Driver comes with utility methods for parsing JSON to BSON and serializing BSON to JSON.
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
DBObject dbObj = ... ;
String json = JSON.serialize( dbObj );
DBObject bson = ( DBObject ) JSON.parse( json );
The driver can be found here: https://mongodb.github.io/mongo-java-driver/
Use Document.parse(String json) from org.bson.Document. It returns Document object which is type of Bson.
The easiest way seems to be to use a JSON library to parse the JSON strings into a Map and then use the putAll method to put those values into a BSONObject.
This answer shows how to use Jackson to parse a JSON string into a Map.
To convert a string json to bson, do:
import org.bson.BasicBSONEncoder;
import org.bson.BSONObject;
BSONObject bson = (BSONObject)com.mongodb.util.JSON.parse(string_json);
BasicBSONEncoder encoder = new BasicBSONEncoder();
byte[] bson_byte = encoder.encode(bson);
To convert a bson to json, do:
import org.bson.BasicBSONDecoder;
import org.bson.BSONObject;
BasicBSONDecoder decoder = new BasicBSONDecoder();
BSONObject bsonObject = decoder.readObject(out);
String json_string = bsonObject.toString();
You might be interested in bson4jackson project, which allows you to use Jackson data binding to work with BSON (create POJOs from BSON, write as BSON) -- especially since Jackson also work with JSON. So it will allow conversion like you mention, just use different ObjectMapper instanstaces (one that works with JSON, other with BSON).
With Jackson you can either work with full POJOs (declare structure you want) or with simple Maps, Lists and so on. You just need to declare what to type to bind to when reading data (when writing, type is defined by object you pass).
You'll find the answer to your question in the source code of https://github.com/mongodb/mongo/blob/master/src/mongo/db/jsobj.cpp
Which has the BSON to JSON conversion.
Basically, stuff like
ObjectId("XXX") -> { "$oid" : "XXX" }
/XXX/gi -> { "$regex" : "XXX", "$options" : "gi" }
and so on...
I would suggest using the toJson() and parse(String) methods of the BasicDBObject, because the JSON utility class has been #Depricated.
import com.mongodb.BasicDBObject;
public static BasicDBObject makeBsonObject(String json) {
return BasicDBObject.parse(json);
}
public static String makeJsonObject(BasicDBObject dbObj) {
return dbObj.toJson();
}
I am not sure about java but the mongoDB CPP driver has a function type
BSONObj fromjson(string)
which returns a BSONObj according to the string passed. There should be a same function in Java too.
Related
Is there a way in Java/J2ME to convert a string, such as:
{name:"MyNode", width:200, height:100}
to an internal Object representation of the same, in one line of code?
Because the current method is too tedious:
Object n = create("new");
setString(p, "name", "MyNode");
setInteger(p, "width", 200);
setInteger(p, "height", 100);
Maybe a JSON library?
I used a few of them and my favorite is,
http://code.google.com/p/json-simple/
The library is very small so it's perfect for J2ME.
You can parse JSON into Java object in one line like this,
JSONObject json = (JSONObject)new JSONParser().parse("{\"name\":\"MyNode\", \"width\":200, \"height\":100}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("width"));
The simplest option is Jackson:
MyObject ob = new ObjectMapper().readValue(jsonString, MyObject.class);
There are other similarly simple to use libraries (Gson was already mentioned); but some choices are more laborious, like original org.json library, which requires you to create intermediate "JSONObject" even if you have no need for those.
GSON is a good option to convert java object to json object and vise versa.
It is a tool provided by google.
for converting json to java object use: fromJson(jsonObject,javaclassname.class)
for converting java object to json object use: toJson(javaObject)
and rest will be done automatically
For more information and for download
You can do this easily with Google GSON.
Let's say you have a class called User with the fields user, width, and height and you want to convert the following json string to the User object.
{"name":"MyNode", "width":200, "height":100}
You can easily do so, without having to cast (keeping nimcap's comment in mind ;) ), with the following code:
Gson gson = new Gson();
final User user = gson.fromJson(jsonString, User.class);
Where jsonString is the above JSON String.
For more information, please look into https://code.google.com/p/google-gson/
You have many JSON parsers for Java:
JSONObject.java
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONArray.java
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONStringer.java
A JSONStringer is a tool for rapidly producing JSON text.
JSONWriter.java
A JSONWriter is a tool for rapidly writing JSON text to streams.
JSONTokener.java
A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and JSONArray constructors to parse JSON source strings.
JSONException.java
A JSONException is thrown when a syntax or procedural error is detected.
JSONString.java
The JSONString is an interface that allows classes to implement their JSON serialization.
JSON official site is where you should look at. It provides various libraries which can be used with Java, I've personally used this one, JSON-lib which is an implementation of the work in the site, so it has exactly the same class - methods etc in this page.
If you click the html links there you can find anything you want.
In short:
to create a json object and a json array, the code is:
JSONObject obj = new JSONObject();
obj.put("variable1", o1);
obj.put("variable2", o2);
JSONArray array = new JSONArray();
array.put(obj);
o1, o2, can be primitive types (long, int, boolean), Strings or Arrays.
The reverse process is fairly simple, I mean converting a string to json object/array.
String myString;
JSONObject obj = new JSONObject(myString);
JSONArray array = new JSONArray(myString);
In order to be correctly parsed you just have to know if you are parsing an array or an object.
Use google GSON library for this
public static <T> T getObject(final String jsonString, final Class<T> objectClass) {
Gson gson = new Gson();
return gson.fromJson(jsonString, objectClass);
}
http://iandjava.blogspot.in/2014/01/java-object-to-json-and-json-to-java.html
Like many stated already, A pretty simple way to do this using JSON.simple as below
import org.json.JSONObject;
String someJsonString = "{name:"MyNode", width:200, height:100}";
JSONObject jsonObj = new JSONObject(someJsonString);
And then use jsonObj to deal with JSON Object. e.g jsonObj.get("name");
As per the below link, JSON.simple is showing constant efficiency for both small and large JSON files
http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/
JSON IO is by far the easiest way to convert a JSON string or JSON input stream to a Java Object
String to Java Object
Object obj = JsonReader.jsonToJava("[\"Hello, World\"]");
https://code.google.com/p/json-io/
This is an old question and json-simple (https://code.google.com/p/json-simple/) could be a good solution at that time, but please consider that project seems not to be active for a while !
I suggest the Gson which is now hosted at: https://github.com/google/gson
If performance is your issue you can have a look at some benchmarks http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/ which compare.
Apart from www.json.org you can also implement your own parser using javacc and matching your personnal grammar/schema.
See this note on my blog : http://plindenbaum.blogspot.com/2008/07/parsing-json-with-javacc-my-notebook.html
I've written a library that uses json.org to parse JSON, but it will actually create a proxy of an interface for you. The code/JAR is on code.google.com.
http://fixjures.googlecode.com/
I don't know if it works on J2ME. Since it uses Java Reflection to create proxies, I'm thinking it won't work. Also, it's currently got a hard dependency on Google Collections which I want to remove and it's probably too heavyweight for your needs, but it allows you to interact with your JSON data in the way you're looking for:
interface Foo {
String getName();
int getWidth();
int getHeight();
}
Foo myFoo = Fixjure.of(Foo.class).from(JSONSource.newJsonString("{ name : \"foo name\" }")).create();
String name = myFoo.getName(); // name now .equals("foo name");
Just make a Json object in java with the following Json String.In your case
{name:"MyNode", width:200, height:100}
if the above is your Json string , just create a Json Object with it.
JsonString ="{name:"MyNode", width:200, height:100}";
JSONObject yourJsonObject = new JSONObject(JsonString);
System.out.println("name=" + yourJsonObject.getString("name"));
System.out.println("width=" + yourJsonObject.getString("width"));
Jackson for big files, GSON for small files, and JSON.simple for handling both.
I am writing java code trying to convert an IPentahoResultSet to JSON so I can send it to a server using apache commons httpclient. I could not find any way to convert this pentaho result set to JSON. Any help will be appreciated.
I have tried this code to serialize it, but it does not work. I think it is meant to serialize classes not resultsets.
import flexjson.JSONSerializer;
import org.pentaho.commons.connection.marshal.MarshallableResultSet;
.
.
.
IPentahoResultSet data;
//data will contain result of executing and MDX against Mondrian
MarshallableResultSet result = new MarshallableResultSet();
result.setResultSet(data);
JSONSerializer serializer = new JSONSerializer();
String json = serializer.deepSerialize( result );
I want to use XStream to convert a java hash to a json hash. I feel like this should be easier than it seems. What I'm looking for is a way to make:
Map<String, String> map = new HashMap<String, String>();
map.put("first", "value1");
map.put("second", "value2");
become
{'first' : 'value1', 'second' : 'value2' }
The closes I have converts it into a series of arrays.
XStream xstream = new XStream(new JettisonMappedXmlDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
xstream.toXML(map);
which becomes
[["first", "value1"], ["second", "value2"]]
I feel like converting a java hash to json hash should be straight forward. Am I missing something?
The thing is that XStream is first and foremost designed to marshal and unmarshal Java objects to XML, JSON being just an afterthought, it most certainly has the least elegant support.
The technical problem being that as XStream must support both - XML and JSON formats, JSON map representation suffers, as there is no native way to represent a map-like structures in XML.
You can try to use the "official" json lib for java from json.org.
Calling:
JSONObject jsobj = new JSONObject(map);
String strJson = jsobj.toString();
I had similar issues when converting to jSon. My solution to this problem was to have the string already formatted to JSon before dropping into the file (in my case a database). The most efficient process I have come up with so far was to create a toJson function inside my classes to work just like toString.
Example:
Converts the objects data output string into Json format
public JsonObject toJson()
{
JsonObject temp = new JsonObject();
temp.addProperty(tagName,floatData);
return temp;
}
So for you, implement a similar process while populating your map.
I am using org.json api to convert xml to json. The problem is certain tags in my xml contain non string values (i.e., int, boolean, double etc...).
The code I am using below, is successfully converting xml to json, but the primitive data types are converted to string in the json response. For eg: <age>10<age> in xml gets converted to {"age" : "10" } in which the value 10 in json is a String which should be an Integer. For example {"age" : 10 }.
The xml input which I give for conversion, is dynamic and will change frequently. But for the sake of showing it as an example, I am saving the xml as a String. The dynamically generated xml code will be saved in a string variable.
Can anyone help me out in converting the xml to json, while preserving the data types? Below is the code
import org.json.*;
public class XmlToJson {
private static String xmlCode =
"<handler>
<price>10</price>
<item>rice</item>
<VALUE>3434</VALUE>
</handler>
<flow>
</flow>";
public static void main(String[] args) throws JSONException{
JSONObject xmlJsonObj=null;
xmlJsonObj = XML.toJSONObject(xmlCode);
System.out.println(xmlJsonObj.toString(1));
}
}
Sample output:
{
"flow": "",
"handler": {
"VALUE": "3434",
"item": "rice",
"price": "10"
}
}
The expected behavior is:
{
"flow": "",
"handler": {
"VALUE": 3434,
"item": "rice",
"price": 10
}
}
You should have a look at my open source library unXml, which parses xml, and outputs Json. It's written for Java 8, and uses the (awesome) Jackson Json-library.
UnXml is available on Maven Central.
Given this xml (Added a root to make wellformed)
<root>
<handler>
<price>10</price>
<item>rice</item>
<VALUE>3434</VALUE>
</handler>
<flow></flow>
</root>
You create a parser like this
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.Parsing;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;
public class XmlParser {
public ObjectNode parseXml(String inputXml){
Parsing parsing = ParsingFactory.getInstance().create();
Document document = parsing.xml().document(inputXml);
Parser<ObjectNode> parser = parsing.obj("root")
.attribute("flow")
.attribute("handler", "handler", parsing.obj()
.attribute("price", "price", parsing.number())
.attribute("item")
.attribute("value", "VALUE", parsing.with(Integer::parseInt))
)
.build();
ObjectNode result = parser.apply(document);
return result;
}
}
Which will return this Json
{
"handler":{
"item":"rice",
"price":10.0,
"value":3434
},
"flow":""
}
If your schema is set, you can go through databinding with POJOs ( convert XML into JSOs,
convert POJOs to JSON ) - there is a lot of databinding tools and I would recomment those working on top of pull-model ( XStream for XML, GSON for JSON - but there is a rich choice
to pich your favorite )
If you are better on XML side, you can also write XSLT transformation which will convert XML to whatever you like , also JSON - though I personally find JavaBeans way easier
I second Konstantin's suggestion of using POJOs in-between XML and JSON -- otherwise you will be having endless problems due to mismatch between the two. Specifically, XML has "native" way of expressing arrays/Lists, so handling of empty and single-element lists/arrays typically produces odd results.
My suggestion would be to use Jackson for JSON and either JAXB or Jackson XML-data-binding for XML -- that way you can also use JAXB annotations for extra information, if naming has to be changed or so.
And whatever else you use, dump org.json package; alternatives are better nowadays so that package serves mostly as historical relic (it was useful when alternatives weren't around).
Is there a way in Java/J2ME to convert a string, such as:
{name:"MyNode", width:200, height:100}
to an internal Object representation of the same, in one line of code?
Because the current method is too tedious:
Object n = create("new");
setString(p, "name", "MyNode");
setInteger(p, "width", 200);
setInteger(p, "height", 100);
Maybe a JSON library?
I used a few of them and my favorite is,
http://code.google.com/p/json-simple/
The library is very small so it's perfect for J2ME.
You can parse JSON into Java object in one line like this,
JSONObject json = (JSONObject)new JSONParser().parse("{\"name\":\"MyNode\", \"width\":200, \"height\":100}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("width"));
The simplest option is Jackson:
MyObject ob = new ObjectMapper().readValue(jsonString, MyObject.class);
There are other similarly simple to use libraries (Gson was already mentioned); but some choices are more laborious, like original org.json library, which requires you to create intermediate "JSONObject" even if you have no need for those.
GSON is a good option to convert java object to json object and vise versa.
It is a tool provided by google.
for converting json to java object use: fromJson(jsonObject,javaclassname.class)
for converting java object to json object use: toJson(javaObject)
and rest will be done automatically
For more information and for download
You can do this easily with Google GSON.
Let's say you have a class called User with the fields user, width, and height and you want to convert the following json string to the User object.
{"name":"MyNode", "width":200, "height":100}
You can easily do so, without having to cast (keeping nimcap's comment in mind ;) ), with the following code:
Gson gson = new Gson();
final User user = gson.fromJson(jsonString, User.class);
Where jsonString is the above JSON String.
For more information, please look into https://code.google.com/p/google-gson/
You have many JSON parsers for Java:
JSONObject.java
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONArray.java
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONStringer.java
A JSONStringer is a tool for rapidly producing JSON text.
JSONWriter.java
A JSONWriter is a tool for rapidly writing JSON text to streams.
JSONTokener.java
A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and JSONArray constructors to parse JSON source strings.
JSONException.java
A JSONException is thrown when a syntax or procedural error is detected.
JSONString.java
The JSONString is an interface that allows classes to implement their JSON serialization.
JSON official site is where you should look at. It provides various libraries which can be used with Java, I've personally used this one, JSON-lib which is an implementation of the work in the site, so it has exactly the same class - methods etc in this page.
If you click the html links there you can find anything you want.
In short:
to create a json object and a json array, the code is:
JSONObject obj = new JSONObject();
obj.put("variable1", o1);
obj.put("variable2", o2);
JSONArray array = new JSONArray();
array.put(obj);
o1, o2, can be primitive types (long, int, boolean), Strings or Arrays.
The reverse process is fairly simple, I mean converting a string to json object/array.
String myString;
JSONObject obj = new JSONObject(myString);
JSONArray array = new JSONArray(myString);
In order to be correctly parsed you just have to know if you are parsing an array or an object.
Use google GSON library for this
public static <T> T getObject(final String jsonString, final Class<T> objectClass) {
Gson gson = new Gson();
return gson.fromJson(jsonString, objectClass);
}
http://iandjava.blogspot.in/2014/01/java-object-to-json-and-json-to-java.html
Like many stated already, A pretty simple way to do this using JSON.simple as below
import org.json.JSONObject;
String someJsonString = "{name:"MyNode", width:200, height:100}";
JSONObject jsonObj = new JSONObject(someJsonString);
And then use jsonObj to deal with JSON Object. e.g jsonObj.get("name");
As per the below link, JSON.simple is showing constant efficiency for both small and large JSON files
http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/
JSON IO is by far the easiest way to convert a JSON string or JSON input stream to a Java Object
String to Java Object
Object obj = JsonReader.jsonToJava("[\"Hello, World\"]");
https://code.google.com/p/json-io/
This is an old question and json-simple (https://code.google.com/p/json-simple/) could be a good solution at that time, but please consider that project seems not to be active for a while !
I suggest the Gson which is now hosted at: https://github.com/google/gson
If performance is your issue you can have a look at some benchmarks http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/ which compare.
Apart from www.json.org you can also implement your own parser using javacc and matching your personnal grammar/schema.
See this note on my blog : http://plindenbaum.blogspot.com/2008/07/parsing-json-with-javacc-my-notebook.html
I've written a library that uses json.org to parse JSON, but it will actually create a proxy of an interface for you. The code/JAR is on code.google.com.
http://fixjures.googlecode.com/
I don't know if it works on J2ME. Since it uses Java Reflection to create proxies, I'm thinking it won't work. Also, it's currently got a hard dependency on Google Collections which I want to remove and it's probably too heavyweight for your needs, but it allows you to interact with your JSON data in the way you're looking for:
interface Foo {
String getName();
int getWidth();
int getHeight();
}
Foo myFoo = Fixjure.of(Foo.class).from(JSONSource.newJsonString("{ name : \"foo name\" }")).create();
String name = myFoo.getName(); // name now .equals("foo name");
Just make a Json object in java with the following Json String.In your case
{name:"MyNode", width:200, height:100}
if the above is your Json string , just create a Json Object with it.
JsonString ="{name:"MyNode", width:200, height:100}";
JSONObject yourJsonObject = new JSONObject(JsonString);
System.out.println("name=" + yourJsonObject.getString("name"));
System.out.println("width=" + yourJsonObject.getString("width"));
Jackson for big files, GSON for small files, and JSON.simple for handling both.