The code that we already have return us JsonObject. What I want to do is to add a new key and the value for it.
For example, we have an object like this:
{"id":"12","name":"test"}
I want to transform it into this:
{"id":"12","name":"test","status":"complete"}
I didn't find what I need in documentation except using put method. So I wrote this code:
JsonObject object = getJsonObject();
JsonString val = new JsonString() {
public JsonValue.ValueType getValueType() {
return JsonValue.ValueType.STRING;
}
public String getString() {
return "complete";
}
public CharSequence getChars() {
return (CharSequence) "complete";
}
};
object.put("status", val);
But it doesn't work, crashing with :
java.lang.UnsupportedOperationException
I can't understand what is wrong. Have I any other option to complete such a task?
I don't think JsonObject instances are meant to be modified.
I think your best option is to create a new object, copy the existing properties and add the new property to it.
You can use https://docs.oracle.com/javaee/7/api/javax/json/JsonObjectBuilder.html
Not sure if object.put works but you can use the following way to append the details to JSON value:
You can create a different JSON object with the key and value that you want to add to the JSON object and the user object.merge(status, complete, String::concat);
merge() checks for the key:'status' in your JSON object if it does'nt find it then it adds that key:value pair or else it replaces it
.You are not able to compile it because you may not be using jre 1.8.
I've Just verified the following method:
Just create a new JSONObject(org.json.JSONObject not javax.json.JsonObject)
JSONObject modifiedJsonObject= new JSONObject(object.toString());
modifiedJsonObject.put("status", "complete");
Related
In JavaScript we can do:
function foo() {
...
return {
attr1 : ... ,
attr2 : ...,
};
}
But what is its equivalent in Java?
Because I want to return a custom Json object from my controller after an ajax call and I want to create a new bean.
As Java dictates, you should create a new class and convert it to JSON. Also, you can use Map<String,Object> to accomplish the same thing. To generate following JSON:
{
"attr1":1,
"attr2":2
}
you can use following code:
Map<String,Object> map = new HashMap<>(3);
map.put("attr1", 1);
map.put("attr2", 2);
and convert it to JSON.
P.S.: HashMap in Java causes your heap to increase and unnecessary garbage, so I specified just enough size to keep two elements.
I have a model object which is initialized with default values. To refresh the content of object I call an web service and get the response and get the content from json object.
I want to check If json response contains the object or not. If it does then call the setter and set the data and if it doesn't then leave then don't set it. I have approx 300 fields in my object. How I can do it with less code. I am listing my current approach.
My Model object is like
public class MyObject {
private String str1 = "Initial Value1";
private String str2 = "Initial Value2";
public void setStr1(String str1)
{
this.str1 = str1;
}
public void setStr2(String str2)
{
this.str2 = str2;
}
public String getStr1(){
return str1;
}
public String getStr2(){
return str2;
}
}
my json response be like
{
"val_one":"New Value1",
"val_two":"New_value2"
}
Now at run time I need to set the value from json response
MyObject myObject = new MyObject();
if(jsonObject.has("val_one"));
myObject.setStr1(jsonObject.get("val_one"));
if(jsonObject.has("val_two"));
myObject.setStr2(jsonObject.get("val_two"));
Now how to do it in a better and efficient
If both sides are using JAVA then why not just use json-io. You can create an object as normal. ie
Animal a = new Aminmal() andimal.setName("bob");
Then use json-io to make it into json -- stream to where ever it needs to be... use json io to change back to object
This can be done using
JsonWriter.objectToJson(Object o);
JsonReader.jsonToJava(String json);
https://code.google.com/p/json-io/
json-io is also extremely light weight and quicker than most if not all other third party json library's that I have used.
That being said if you want to have more control on the output ie.. date conversions etc.. then look at GSON.
https://code.google.com/p/google-gson/
Another option, in addition to the other suggestions is gson. Here the link for gson information.
Essentially the idea with gson being that you define an object to represent the JSON structure that you are receiving. So somewhat like what you have now, you'd just need to change the object attributes to match the names of the JSON fields, ie 'val_one' and 'val_two'.
Then you just need to use gson to create the object from the JSON text, eg:
Gson gson = new GsonBuilder().create();
MyObject json = gson.fromJson(jsonStr, MyObject.class);
Why do you want to take of the object model mapping yourself? If you take spring then you can use the jackson mapper and have it all done for you.
If you don't want to use spring then you still can use jackson2 and let it handle the parsing:
http://wiki.fasterxml.com/JacksonRelease20
So, I get some JSON values from the server but I don't know if there will be a particular field or not.
So like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
}
And sometimes, there will be an extra field like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited",
"club":"somevalue"
}
I would like to check if the field named "club" exists so that at parsing I won't get
org.json.JSONException: No value for club
JSONObject class has a method named "has":
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for name. The mapping may be NULL.
You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) {
String status = json.getString("status"));
}
if (json.has("club")) {
String club = json.getString("club"));
}
You can also check using 'isNull' - Returns true if this object has no
mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club"))
String club = json.getString("club"));
you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also
use optString instead of getString:
Returns the value mapped by name if it exists, coercing it if
necessary. Returns the empty string if no such mapping exists
just before read key check it like before read
JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
//it's contain value to be read operation
}
else
{
//it's not contain key club or isnull so do this operation here
}
isNull function definition
Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL.
official documentation below link for isNull function
http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)
You can use has
public boolean has(String key)
Determine if the JSONObject contains a specific key.
Example
JSONObject JsonObj = new JSONObject(Your_API_STRING); //JSONObject is an unordered collection of name/value pairs
if (JsonObj.has("address")) {
//Checking address Key Present or not
String get_address = JsonObj .getString("address"); // Present Key
}
else {
//Do Your Staff
}
A better way, instead of using a conditional like:
if (json.has("club")) {
String club = json.getString("club"));
}
is to simply use the existing method optString(), like this:
String club = json.optString("club);
the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.
Try this:
let json=yourJson
if(json.hasOwnProperty(yourKey)){
value=json[yourKey]
}
Json has a method called containsKey().
You can use it to check if a certain key is contained in the Json set.
File jsonInputFile = new File("jsonFile.json");
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();
if frameObj.containsKey("person") {
//Do stuff
}
Try this
if(!jsonObj.isNull("club")){
jsonObj.getString("club");
}
I used hasOwnProperty('club')
var myobj = { "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
};
if ( myobj.hasOwnProperty("club"))
// do something with club (will be false with above data)
var data = myobj.club;
if ( myobj.hasOwnProperty("status"))
// do something with the status field. (will be true with above ..)
var data = myobj.status;
works in all current browsers.
You can try this to check wether the key exists or not:
JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
object.get("key");
//etc. etc.
}
I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {} and using has(String key) doesn't make any sense.
So you can directly write if (jsonObject.length() > 0) and do your things.
Happy learning!
You can use the JsonNode#hasNonNull(String fieldName), it mix the has method and the verification if it is a null value or not
I have a REST api GET call that takes an array of strings formatted as JSON. I'd like to use Jersey to convert that array of strings to something like a string array or List. I've reviewed http://jersey.java.net/nonav/documentation/latest/json.html, but it looks like Jersey wants me to create an object that specifies how it should be mapped, which I really don't want to do because it's just a simple array.
#GET
public Response get(#QueryParam("json_items") String requestedItems) throws IOException
{
//Would like to convert requestedItems to an array of strings or list
}
I know there are lots of libraries for this - but I'd prefer to use Jersey and not introduce any new libraries.
Create a wrapper object for you data (in this case the Person class) and annotate it with #XMLRootElement
Your post method should look like this
#POST
#Consumes(MediaType.APPLICATION_JSON)
public void post(List<Person> people) {
//notice no annotation on the method param
dao.putAll(people);
//do what you want with this method
//also best to return a Response obj and such
}
this is the right way to do this stuff where the data is sent in the request.
but if you want to have a QueryParam as the JSON data you can do this
say your request param looks like this:
String persons = "{\"person\":[{\"email\":\"asdasd#gmail.com\",\"name\":\"asdasd\"},{\"email\":\"Dan#gmail.com\",\"name\":\"Dan\"},{\"email\":\"Ion#gmail.com\",\"name\":\"dsadsa\"},{\"email\":\"Dan#gmail.com\",\"name\":\"ertert\"},{\"email\":\"Ion#gmail.com\",\"name\":\"Ion\"}]}";
you notice that its a JSONObject named "person" that contains a JSONArray of other JSONObjets of type Person with name an email :P
you can itterate over them like this:
try {
JSONObject request = new JSONObject(persons);
JSONArray arr = request.getJSONArray("person");
for(int i=0;i<arr.length();i++){
JSONObject o = arr.getJSONObject(i);
System.out.println(o.getString("name"));
System.out.println(o.getString("email"));
}
} catch (JSONException ex) {
Logger.getLogger(JSONTest.class.getName()).log(Level.SEVERE, null, ex);
}
sry
Just try to add to your Response the array, like
return Response.ok(myArray).build();
and see what happen.
If it's just a very simple array it should be parsed without any problem.
EDIT:
If you want to receive it then just accept an array instead of a String. Try with a List or something like this.
Otherwise you can try to parse it using an ObjectMapper
mapper.readValue(string, List.class);
I'm building a json object in java. I need to pass a function into my javascript and have it validated with jquery $.isFunction(). The problem I'm encountering is I have to set the function in the json object as a string, but the json object is passing the surrounding quotes along with object resulting in an invalid function. How do I do this without having the quotes appear in the script.
Example Java
JSONObject json = new JSONObject();
json.put("onAdd", "function () {alert(\"Deleted\");}");
Jquery Script
//onAdd output is "function () {alert(\"Deleted\");}"
//needs to be //Output is function () {alert(\"Deleted\");}
//in order for it to be a valid function.
if($.isFunction(onAdd)) {
callback.call(hidden_input,item);
}
Any thoughts?
You can implement the JSONString interface.
import org.json.JSONString;
public class JSONFunction implements JSONString {
private String string;
public JSONFunction(String string) {
this.string = string;
}
#Override
public String toJSONString() {
return string;
}
}
Then, using your example:
JSONObject json = new JSONObject();
json.put("onAdd", new JSONFunction("function () {alert(\"Deleted\");}"));
The output will be:
{"onAdd":function () {alert("Deleted");}}
As previously mentioned, it's invalid JSON, but perhaps works for your need.
You can't. The JSON format doesn't include a function data type. You have to serialise functions to strings if you want to pass them about via JSON.
Running
onAdd = eval(onAdd);
should turn your string into a function, but it's buggy in some browsers.
The workaround in IE is to use
onAdd = eval("[" + onAdd + "]")[0];
See Are eval() and new Function() the same thing?