Treves the JSON object and manipulate the value in java - java

What im trying to do is
JSON:
{
aKey:{
aChildKey:""
},
bKey:""
}
expected:
aKey:{
aChildKey:"aKey.aChildKey"
},
bKey:"bKey"
}
Please can some one help me in getting the expected the value

You need to deserialize the JSON into an object, set the values, then serialize it back into JSON. There are a number of libraries you can use for this, like org.json, gson, or Jackson. Those libraries also allow you to modify the value directly. For example, using org.json, you can do something like this:
JSONObject jsonObject = new JSONObject(myJsonString);
jsonObject.getJSONObject("akey").put("aChildKey","aKey.aChildKey");
See How to parse JSON in Java

Related

Is there a better/easier way to update a json file in Java?

Say, I have a json file like below:
[{
"obj1_key1":"aa",
"obj1_array":[{"e1":"11"},{"e2":"22"}]
},
{
"obj2_key1":"cc",
"obj2_key2":"dd"
}]
Now I want update the file into something like below:
[{
"obj1_key1":"aa",
"obj1_array":[{"e1":"11"},{"e2":"22"},{"e3":"333"}]
},
{
"obj2_key1":"cc",
"obj2_key2":"dd"
}]
I tried using ObjectMapper to parse the file like
JsonNode jsonFile = new ObjectMapper().readTree(new File("file.json");
however then I need to find the obj1_array and append a json object, then write the json object back to the file. And I don't think the way I load the json file as a JsonNode is a easy way because I should convert it between Json/JsonArray back and forth. So I'm wondering is there a simpler way to make this work? Really appreciate that.
if it is just a one-off case, you can use your preferred mechanism, but if it is going to used often, I would prefer
Convert the JSON to a POJO ( using some parser eg Jackson )
Update the requisite fields
Return the Json object.

How to obtain all the matches using a regex in java [duplicate]

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.

get the value out of a long string with multiple values

I have a string:
{"name":"value", "name2":"value2" ... "name3":"value3"}
I would like to search by a name and get the value of it.
But I never saw this format before.. so I have no idea what to look for. Thanks for any hint.
As this is JSON, you need a JSON parsing library. This example uses Jackson:
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(someURLhere);
// access "name1" using node.get("name1").textValue(), etc
To me this looks like JSON, although I could be wrong.
If you're working in Javascript, you can do this:
var JSONobject = {"name":"value", "name2":"value2" ... "name3":"value3"};
and then get your desired value with:
JSONobject.name;
(This should return "value")
Other languages have libraries available. PHP has JSON support buildin (json_decode), and for Java my person favorite is GSON.
Its JSON formet use json jar to handle this formet... Ex: JSONObject jsonObject = new JSONObject (yourString) ; for getting name value you should use jsonObject. get ( "name" ) ;

Create JSON object and convert it to String in Java

I need to send a quite long JSON header through an http post. In Python was like this:
self.body_header = {
"client": self.client_name,
"clientRevision": self.client_version,
"uuid": str(uuid.uuid4()),
"session": self.get_sessionid()}
self.body = {
"header": self.body_header,
"country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
"privacy": 1}
I need to do something similar in Java, ie, create somehow a JSON struct, convert it to a String and send it via http.
The question is, how can I achieve that easily? Any useful libraries? I know how to send it, but not how to build it and then create a String.
Thank you all.
You can use gson.
You can create a Java Object (POJO) and serialize it as JSON by doing:
Gson gson = new Gson();
String json = gson.toJson(yourObject);
You can then send the string over HTTP.
If you do not want to go the POJO route, you can still create the JSON struct using JsonElement, JsonArray, JsonObject in the Gson API.
I like the original org.json
i think STO had a similar discussion https://stackoverflow.com/questions/338586/a-better-java-json-library

Convert a JSON string to object in Java ME?

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.

Categories