Parse json array with quotes around it - java

I'm calling 3rd party API and receiving as a response next string:
"[{\"name\":\"name\",\"id\":1}]"
As I see it's not valid json because it has quotes around it. Is it possible somehow to map it to java object with jackson, gson libraries?
Or anyway I should write my custom converter/deserializer?

You don't need a custom converter or deserializer. You could write one of course, but I wouldn't encourage you to do so. Be explicit about what is happening here, especially when you are working in a team. It's the other side that is at fault here, they are not outputting valid JSON.
With Jackson, deserialize their output this way:
ObjectMapper mapper = new ObjectMapper();
String json = theirOutput.substring(1, theirOutput.length - 1);
Object myObject = mapper.readValue(json, MyObject.clas);
Put some documentation above why you do it this way so everybody understands what's happening here. In my opinion this is a much cleaner solution than writing a custom converter or deserializer.

Related

java objectmapper readvalue reading wrong string

I need to convert a certain JSON string to a Java object. I am using Jackson ObjectMapper for reading the JSON. The JSON String is something like this:-
"{"emailId":"gmail#rajnikant.com","accessToken":"accTok"}4".
When I am using objectMapper.readValue() for reading the JSON string to a specific destination class, it should throw an exception because of the JSON string being appended by 4. What should I do so that only valid JSON can be read and in other cases it will throw an exception?
To Jackson, GSON and others, a JSON string with some characters appended after the last } is valid JSON as long as what is contained between the {} is valid JSON.
As stated by a member of FasterXML (Jackson) team:
Yes. This is by design. If you want to catch such problems, you need to construct JsonParser, advance it manually. Existence of multiple root-level values is not considered a validity problem.
Reference: https://github.com/FasterXML/jackson-databind/issues/726
So if you need to enforce "clean" JSON you'll have to extend the default parser with your own functionality. However, IMO if it's OK to the default parser it should be OK to you too (unless we're dealing with some inter-language incompatibility scenario here).

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)

Parse JSON String into raw Java types using Jackson?

I would like to parse some JSON string the represents either an array or a map in the simplest possible way. I have the whole JSON string, no streaming is needed.
What I would like to do is something as similar as possible to this:
Object obj = parseJSON(theString);
Where obj would then hold an instance of either a Map or a List (I cannot know in advance which). The JSON object can be arbitrarily nested with maps and arrays but all types will be representable as basic Java types: String, Integer, Double, Boolean plus Map and ArrayList, nothing else.
All the simple examples I have found so far require me to know what the type is and which types I want, but I want to let all this do the JSON parser since I simply will not know in advance what I get.
If Jackson is not the best library to do this, what else could I use?
All you need to do is this:
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(theString, Map.class);
I'm pretty sure this returns a LinkedHashMap, if you care.
And in my opinion, you won't find a better serializer/deserializer for Java <-> JSON than Jackson. But there are many others like GSON.
Silly question, simple answer:
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.readValue(theString, Object.class);
That seems to do exactly what I want. And it's so obvious too!
Another option should you decide to ditch Jackson (Jackson is fine, I'm quite agnostic in the JSON wars) is json-simple.
JSONObject jObject = JSONValue.parse(String jsonString);
Since JSONObject extends java.util.HashMap everything should work.

Parsing a json object which has many fields

I want to parse json from a server and place it into a class. I use json4s for this. The issue is that a json object contains too many fields, it's about 40-50 of them, some of them have the long names.
I wonder, what will be a sensible way to store all of them, will I have to create 40-50 fields in a class? Remember, some of them will have the long names, as I said earlier.
I use Scala, but a Java's approach might be similar to it, so I added a tag of Java also.
I don't know json4s but in Jersey with Jackson, for example, you can use a Map to hold the Json data or you can use a POJO with all those names.
Sometimes its better to have the names. It makes the code much easier to understand.
Sometimes its better to use a Map. For example, if the field names change from time to time.
If I recall it correctly, using pure Jackson you do something like this:
String jsonString = ....; // This is the string of JSON stuff
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory); // A Jackson class
Map<String,Object> data = mapper.readValue(jsonString, HashMap.class);
You can use a TypeReference to make it a little cleaner as regards the generics. Jackson docs tell more about it. There is also more here: StackOverflow: JSON to Map
There are generally two ways of parsing json to object
1) Parse json to object representation.
the other which might suit you as you mention that your object has too many fields is amap/hashtable, or you could just keep it as JObject, an get fields ehrn you need them

What is the the best way to convert JSONObject to a domain object?

I have a rest service returning some data. I use Restlet client api as shown below to access this service. As you can see, it returns org.json.JSONObject. Is there a easy way to map this to the domain object (may be through annotations?) or should I have to write code to create the domain object?
Representation entity = new ClientResource(uri).get();
JSONObject json = new JsonRepresentation(entity).getJsonObject();
May be you can leverage from Gson library which has a function you need:
// Convert JSON into Java object
SomeObj obj = gson.fromJson(jsonObjStr, SomeObj.class)
You can read more here...
While there are decent APIs for easily mapping between Java data structures, e.g., from the JSONObject to your preferred data structure, since the incoming data format is JSON, I'd much prefer to just use a good JSON-to/from-Java API like Jackson. Depending on the preferred transformation details, the solution might be just one simple line of code with such an API.

Categories

Resources