How to modify an existing jsonobject in Java - java

I have an existing jsonobject from the javax.json.JsonObject class.
I can't for the life of me figure out how I can modify the existing values in it. Ideally I'd like to do something like this:
if(object.getString("ObjectUUID").length()==0){
object.put("ObjectUUID", UUID.randomUUID().toString());
}
According to the API you aren't allowed to modify that map.
http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
This map object provides read-only access to the JSON object data, and attempts to modify the map, whether direct or via its collection views, result in an UnsupportedOperationException.
Currently I'm getting around the problem with a quick hack but there must be a better solution than this:
if(object.getString("ObjectUUID").length()==0){
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("ObjectUUID", UUID.randomUUID().toString());
for(String key : object.keySet()){
if(!key.equals("ObjectUUID")){
job.add(key, object.get(key));
}
}
object = job.build();
}
So the question how do you modify an existing jsonobject?

Without knowing the structure of the JSON object, it's a bit difficult to provide an answer that addresses your specific problem. The JsonObject instance is immutable, so you can't update it like Jackson's ObjectNode. As you've probably found, the JsonObject.add() method is basically useless, and depending on the implementation, may yield an UnsupportedOperationException. It's puzzling why it exists in the first place.
The way to modify the object is to create a JsonObjectBuilder instance that wraps the original JsonObject. If the object instance was your original JsonObject you'd probably want to do something like this:
if(object.getString("ObjectUUID").length()==0){
object job = Json.createObjectBuilder(object)
.add("ObjectUUID", UUID.randomUUID().toString())
.build();
}
This took me a while to understand myself, and it gets a but more verbose if you have nested objects, etc.. If you're updating or replacing an object or array, you don't need to explicitly remove it before adding. There's pros and cons of the approach, but it beats the monthly ceremony of updating Jackson on a monthly basis :)

I think there is no other way to modify a javax.json.JsonObject.
You should consider using jackson-databind.

GSON Guide;
obj.addProperty("Id", "001");
System.out.println("Before: " + obj.get("Id")); // 001
obj.addProperty("Id", "002");
System.out.println("After: " + obj.get("Id")); // 002

Related

How to copy all the values from one JSONObject to another?

I understand that it's perfectly possible to copy each individual component over one by one, but it's extremely messy to do and rather ugly. Isn't there a simpler way to copy all the values from one JSONObject to another? Important to note, I am using json-lib. I'm not opposed to switching tools if it's absolutely necessary. Point is, this is a rather inefficient way of doing things.
After hours of searching, I finally found the answer. I'm sort of embarrased that it's this simple.
~
Json-lib has a beautiful feature that allows you to take your current JSONObject and parse the entirety of the JSONObject into a String. And there already exists a method to build a JSONObject from a String. Therefore, all you need to do is turn the JSONObject into a String, and then back into a JSONObject. You could store the string as a variable (or use it as a return value), then simply take your preexisting JSONObject reference and use the method to rebuild the JSONObject from the String. Simple as that.
EDIT - thought I would give a quick code example
JSONObject a = /* pretend a has 100 elements inside */
String temp = a.toString();
JSONObject b = JSONObject.fromObject(temp);
String temp2= b.toString();
if(temp.equals(temp2)){System.out.println("Well done.");}

Parsing JSON string and preserving key-data order when using json-simple without manually constructing HashMap

I know that this topic has been talked about, and the use of a LinkedHashMap is a 'hacky' way to maneuver this, but if I'm given thousands of JSON strings as input, and eventually want to output them back in their original form, is there anyway to preserve the order without manually constructing LinkedHashMaps.
For example a string like this
{"key":1,"surname":"Reed","given":"Ryan","address":{"state":"CA","postal":"90210"},"gender":"M"}
Right now if I parse the object like so:
JSONObject jsonObject = (JSONObject) parser.parse(str);
System.out.println(jsonObject);
My output will look like this:
{"surname":"Reed","gender":M,"address":{"postalCode":"90210","state":"CA"},"key":1,"given":"Ryan"}
Is there anyway I can get the output to match exactly like the given input?
In Json property structure, order does not matter. but if you have specific order in your mind you can use Jackson to order them in you desirable way, both in your server and client apps.
https://www.baeldung.com/jackson
http://www.davismol.net/2016/10/24/jackson-json-using-jsonpropertyorder-annotation-to-define-properties-serialization-order/
I think it is impossible by default.
You can refer to this RFC https://www.ietf.org/rfc/rfc4627.txt
An array is an ordered sequence of zero or more values.
If you want to hack it you can override the data structure and use the data structure which preserves the order.

How to store list of realm object to Arraylist in android [duplicate]

I have RealmResults that I receive from Realm like
RealmResults<StepEntry> stepEntryResults = realm.where(StepEntry.class).findAll();
Now I want convert RealmResults<StepEntry> to ArrayList<StepEntry>
I have try
ArrayList<StepEntry> stepEntryArray = new ArrayList<StepEntry>(stepEntryResults));
but the item in my ArrayList is not my StepEntry object, it is StepEntryRealmProxy
How can I convert it?
Any help or suggestion would be great appreciated.
To eagerly read every element from the Realm (and therefore make all elements in the list become unmanaged, you can do):
List<StepEntry> arrayListOfUnmanagedObjects = realm.copyFromRealm(realmResults);
But you generally have absolutely no reason to do that unless you want to serialize the objects with GSON (specifically, because it reads field data with reflection rather than with getters), because Realm was designed in such a way that the list exposes a change listener, allowing you to keep your UI up to date just by observing changes made to the database.
The answer by #EpicPandaForce works well. I tried this way to optimize my app performance and I find the following is a bit faster. Another option for people who prefer speed:
RealmResults<Tag> childList = realm.where(Tag.class).equalTo("parentID", id).findAll();
Tag[] childs = new Tag[childList.size()];
childList.toArray(childs);
return Arrays.asList(childs);
In Kotlin:
var list : List<Student>: listof()
val rl = realm.where(Student::class.java).findAll()
// subList return all data contain on RealmResults
list = rl.subList(0,rl.size)

javax.json objects have same methods, but they're not implementations of a common interface. How to cast?

I'm dealing with the strange javax.json library. So here's the problem:
I need to cast an Object of type JsonValue to either JsonObject or JsonArray so I can call the methods getJsonObject and getJsonArray of it. Both JsonArray and JsonObject have the same method names with the same functionalities but they're not implemented methods, they are methods defined on each of them! See: JsonObject, JsonArray.
The obvious solution would be to verify the type and then cast depending on the verified type, like this:
if (current.getValueType().equals(JsonValue.ValueType.OBJECT)) {
current = ((JsonObject) current).getJsonObject(node);
} else if (current.getValueType().equals(JsonValue.ValueType.ARRAY)) {
current = ((JsonArray) current).getJsonObject(node);
}
but it'd require too many repetitions on my code. So I ask:
1) If both JsonObject and JsonArray have the same methods, why they're not implementations of some interface?
2) Is there a more elegant way to cast the object to JsonObject or JsonArray at the same time by using some trick? Do you know any way to make this situation better?
Although the 2 methods on the 2 different objects have the same name, their signatures are in fact different. JsonObject#getJsonObject(String) accepts a String key identifying the value to pull from a JSON object of key-value pairs. JsonArray#getJsonObject(int) accepts an int index identifying which element to pull the value from in a JSON array.
In this case, there is no appropriate common interface that the 2 classes can share. Your code will have to know whether to inspect a JSON object or a JSON array and cast accordingly.
Since the 2 methods in question do not have the same signature, there are not other alternatives for calling them in a "common way". You could potentially use reflection, but this risks making the code more confusing. For example, Apache Commons includes MethodUtils#invokeMethod. You could potentially use that to invoke any method named "getJsonObject", accepting any kind of object (either String or int). Although using this would make it "common code" across both cases, it's potentially confusing for people reading the code later. They'd have to keep track of the fact that this is using reflection, and that the passed argument might be either String or int, and that it really all works out thanks to it being either a JSON object or array. Instead, I would favor just doing the downcast in this case.
Chris is right, Your code will have to know whether to inspect a JSON object or a JSON array and cast accordingly. However, if you are ok with adding an external library, I would recommend gson for parsing Json
This library has JsonElement class which should fit good in your case. look at this to see how it works

Elegant mapping from POJOs to vertx.io's JsonObject?

I am currently working on a vertx.io application and wanted to use the provide mongo api for data storage. I currently have a rather clunky abstraction on top of the stock JsonObject classes where all get and set methods are replaced with things like:
this.backingObject.get(KEY_FOR_THIS_PROPERTY);
This is all well and good for now, but it won't scale particularly well. it also seems dirty, specifically when using nested arrays or objects. For example, if I want to be able to fill fields only when actual data is known, I have to check if the array exists, and if it doesn't create it and store it in the object. Then I can add an element to the list. For example:
if (this.backingObject.getJsonArray(KEY_LIST) == null) {
this.backingObject.put(KEY_LIST, new JsonArray());
}
this.backingObject.getJsonArray(KEY_LIST).add(p.getBackingObject());
I have thought about potential solutions but don't particularly like any of them. Namely, I could use Gson or some similar library with annotation support to handle loading the object for the purposes of manipulating the data in my code, and then using the serialize and unserialize function of both Gson and Vertx to convert between the formats (vertx to load data -> json string -> gson to parse json into pojos -> make changes -> serialize to json string -> parse with vertx and save) but that's a really gross and inefficient workflow. I could also probably come up with some sort of abstract wrapper that extends/implements the vertx json library but passes all the functionality through to gson, but that also seems like a lot of work.
Is there any good way to achieve more friendly and maintainable serialization using vertx?
I just submitted a patch to Vert.x that defines two new convenience functions for converting between JsonObject and Java object instances without the inefficiency of going through an intermediate JSON string representation. This will be in version 3.4.
// Create a JsonObject from the fields of a Java object.
// Faster than calling `new JsonObject(Json.encode(obj))`.
public static JsonObject mapFrom(Object obj)
// Instantiate a Java object from a JsonObject.
// Faster than calling `Json.decodeValue(Json.encode(jsonObject), type)`.
public <T> T mapTo(Class<T> type)
Internally this uses ObjectMapper#convertValue(...), see Tim Putnam's answer for caveats of this approach. The code is here.
I believe Jackson's ObjectMapper.convertValue(..) functions don't convert via String, and Vert.x is using Jackson for managing JsonObject anyway.
JsonObject just has an underlying map representing the values, accessible via JsonObject.getMap(), and a Jackson serializer/deserializer on the public ObjectMapper instance in io.vertx.core.json.Json.
To switch between JsonObject and a data model expressed in Pojos serializable with Jackson, you can do:
JsonObject myVertxMsg = ...
MyPojo pojo = Json.mapper.convertValue ( myVertxMsg.getMap(), MyPojo.class );
I would guess this is more efficient than going via a String (but its just a guess), and I hate the idea of altering the data class just to suit the environment, so it depends on the context - form vs performance.
To convert from Pojo to JsonObject, convert to a map with Jackson and then use the constructor on JsonObject:
JsonObject myobj = new JsonObject ( Json.mapper.convertValue ( pojo, Map.class ));
If you have implied nested JsonObjects or JsonArray objects in your definition, they will get instantiated as Maps and Lists by default. JsonObject will internally re-wrap these when you access fields specifying those types (e.g. with getJsonArray(..).
Because JsonObject is freeform and you're converting to a static type, you may get some unwanted UnrecognizedPropertyException to deal with. It may be useful to create your own ObjectMapper, add the vertx JsonObjectSerializer and JsonArraySerializer, and then make configuration changes to suit (such as DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES in Jackson).
Not sure if I've understood you correctly, but it sounds like you're trying to find a simple way of converting POJOs to JsonObject?
So, we have lots of pojos that we send over the EventBus as JsonObjects
I've found the easiest way is to use the vert.x Json class which has loads of helper methods to convert to / from Json Strings
JsonObject jsonObject = new JsonObject(Json.encode(myPojo));
Sometimes you need to add some custom (de)serializers, but we always stick with Jackson - that is what Vert.x is using so they work out of the box.
What we actually do, is provide an interface like the following:
public JsonObjectSerializable {
public JsonObject toJson();
}
And all our pojos that need to be sent over the EventBus have to implement this interface.
Then our EventBus sending code looks something like (simplified):
public <T extends JsonObjectSerializable> Response<T> dispatch(T eventPayload);
Also, as we generally don't unit test Pojos, adding this interface encourages the developers to unit test their conversion.
Hope this helps,
Will
Try this:
io.vertx.core.json.Json.mapper.convertValue(json.getMap(), cls)
I think that using Gson as you described is the best possible solution at the current time.
While I agree that if a protocol layer was included in Vert.x it would indeed be first prize, using Gson keeps your server internals pretty organised and is unlikely to be the performance bottleneck.
When and only when this strategy becomes the performance bottleneck have you reached the point to engineer a better solution. Anything before that is premature optimisation.
My two cents.
You can try:
new JsonObject().mapFrom(object)

Categories

Resources