Unable to use "as JSON" after upgrading to grails 2.1.1 from grails 1.3.4 - json

I'm in the process of upgrading a grails plugin from 1.3.4 to grails 2.1.1. After upgrading I now have an integration test that fails that was not failing before. It fails on using the "as JSON" (grails.converters.JSON).
#Test
public void testConvertCollectionOfEnvironmentSettingsToJSON() {
EnvironmentSetting setting = configurationService.getEnvironmentSetting('ENFORCE_SCHEMA_INSTANCE_RULE')
def jsonSetting = setting as JSON //exception thrown here
def s = jsonSetting as String
assertNotNull jsonSetting
}
The exception and stacktrace:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'com.company.ipsvc.configuration.domain.EnvironmentSettingAllRevs#48c12420' with class 'com.company.ipsvc.configuration.domain.EnvironmentSettingAllRevs' to class 'grails.converters.JSON'
at com.company.ipsvc.configuration.converter.json.basic.BasicEnvironmentSettingJSONIntegrationTests.testConvertCollectionOfEnvironmentSettingsToJSON(BasicEnvironmentSettingJSONIntegrationTests.groovy:28)
I am able to use encodeAsJSON() successfully. I also have the same issue with as XML.

I think converters (as JSON syntax) will only work on domain objects and collections by default.
To convert arbitrary objects you should use the encodeAsJSON() converter, I believe. Or use an object marshaller, where you tell the converter how to deal with your object.
The docs aren't very clear on this though..
See:
http://grails.org/Converters+Reference (object marshalling section at bottom)
http://grails.org/doc/latest/ref/Plug-ins/codecs.html
But I note that http://grails.org/doc/latest/api/grails/converters/JSON.html#JSON%28java.lang.Object%29 says that the object converts POGOs.. Maybe it means if you have a marshaller?
I did find this reference too:
Notice that the ‘as’ operator is not overloaded for plain objects ...
Domain objects can use the ‘as’ operator to cast an object to JSON, the same as a collection. So unlike POGOs, where they must be massaged into a list or have encodeAsJSON explictly called ...
http://manbuildswebsite.com/2010/02/08/rendering-json-in-grails-part-2-plain-old-groovy-objects-and-domain-objects/
Which seems to describe the situation.

For non-Domain objects, we found that this would crop up when running tests... the solution for us was to use new JSON:
render new JSON( obj )
This would allow the test to work, and the code does the same thing (essentially)

Ran into a similar issue that broke unit test using grails 2.2.1 . At issue was a straight obj as JSON conversion attempt. But this was interpreted as type casting instead.
The workaround is to stuff your obj to be converted into a map like this [data:obj] as JSON

Related

How to convert Model to JSON

When I naively use Jackson to convert to JSON i receive this exception:
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.apache.cayenne.access.DefaultDataRowStoreFactory and no properties discovered to create BeanSerializer
Edit: I'd like to do something like this:
ObjectContext context = cayenneRuntime.newContext();
List<User> users = ObjectSelect.query(User.class).select(context);
JsonObject json = Json.mapper.convertValue(obj, Map.class)
Are there any existing solutions? Thanks
Considering that in a general case Cayenne gives you not just objects, but a virtual graph of objects, serialization to JSON becomes a more quirky topic than it initially appears.
The short answer: you'd have manually build JSON for whatever subgraph of your object graph.
While not a direct answer, it may be worth mentioning that Agrest framework (ex. LinkRest) supports rule-based serialization of Cayenne object graphs to JSON. But it is not a standalone component. I.e. it will only work if you use it for your REST services.

Create JAX-RS Client Post Request with JSON String as Body

I am writing a REST Client for one of the Vendor REST Service. I use jersey 2.x and JSON-P, below are dependencies I add.
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>2.26</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.26</version>
</dependency>
</dependencies>
I successfully write code for GET request and received JSON output. I saved it to a file and used JSON-P to interpret and do my own logic without any issues.
But now I need to write a POST request. When I use CURL as below I am able do it. and want to implement the same using Jeresey 2.x and JSON-P.
curl -v -H "Accept:application/json" -H "Content-Type:application/json" -u user:password -X POST --databinary #./InputParameters.json https://<IP>:<PORT>/Configuration/server
InputParameters.json contents
{
"ip": "10.197.70.16",
"partNumber": 202067,
"model": "IBM P7"
}
When I tried to pass response body as String in JSON format ({"ip": "10.197.70.16", "partNumber": 202067, "model": "IBM P7"}), but didn't work. So tried as JsonObject as below still didn't work.
JsonObject jsonObj = Json.createObjectBuilder()
.add("ip", "10.197.70.16")
.add("partNumber", 202067)
.add("model", "IBM P7")
.build();
response = invocationBuilder.post(Entity.json(jsonObj));
I know core java, based on that experience I jumped into writing this program and got success with GET but not POST. I doubt I am doing something fundamentally wrong with POST.
Let's unpack what you're doing for a bit. First there's this part:
JsonObject jsonObj = Json.createObjectBuilder()
.add("ip", "10.197.70.16")
.add("partNumber", 202067)
.add("model", "IBM P7")
.build();
This creates a javax.json.JsonObject instance. JsonObject, which is part of the JSON-P Java API, is pretty much what it says: a class to represent a JSON object. A JsonObject instance contains a hierarchy of javax.json.JsonValue instances, which conform to more specific types like JsonArray, JsonString, other JsonObjects and so on. In this regard it's not unlike the classes of the DOM API for representing XML documents (let's hope Oracle keeps the API docs at that URL for a while). But JSON is fortunately a lot more straightforward than XML and DOM.
Your jsonObj instance would contain a JsonString instance with value "10.197.70.16" mapped to name "ip", a JsonNumber with value 202067 (probably represented as BigDecimal) mapped to name "partNumber" and so on.
Next your code executes this:
Entity.json(jsonObj)
javax.ws.rs.client.Entity.json(something) basically states that you want to create an entity that will provide the payload for a JAX-RS client invocation with as Content-Type application/json. In other words, the something you create it for must be transformed to a JSON representation when it's sent to the API, which should expect a JSON payload and know how to handle it. Note that Entity.json(...) has a generic type parameter. The method signature is static <T> Entity<t> json(T entity). So you're creating an instance of Entity<JsonObject> with the payload entity jsonObj.
When this is handed over to the post method of a javax.ws.rs.client.Invocation.Builder instance (the post method is actually defined in its parent interface SyncInvoker) the client implementation goes to work.
response = invocationBuilder.post(Entity.json(jsonObj));
It takes the provided Entity instance and its content (our jsonObj), checks what the desired output is of the Entity (this is application/json) and seeks a provider that can turn objects of the given type into that output. In other words, some component must be located that can be given a javax.json.JsonObject and write a representation of it as JSON to an OutputStream. The component handling this could be a javax.ws.rs.ext.MessageBodyWriter that claims it can perform this transformation and was registered to the JAX-RS runtime. Various libraries supply such providers and you can also write your own. This makes JAX-RS extensible to deal with various scenarios, handle non-standard input and output or lets you tune its behaviour. When multiple providers are capable of handling the given entity type and producing the desired output, there are rules to determine which one takes on the job. Note that this can depend on what is on your classpath. There are ways of forcing this explicitly.
The client puts together the invocation through its configuration, using the proper URL, query parameters, HTTP method, headers and so on. The payload is created by writing the entity to an OutputStream in the required format. In your example this results in a POST to the server. When the invocation has been completed you receive a javax.ws.rs.core.Response that you can use to determine the HTTP result code and retrieve a response payload, if any. The readEntity(Class<T> entityType) method of Response works like the reverse of turning an Entity into a payload. It searches for a MessageBodyReader that can interpret the response stream according to the value returned from response.getMediaType() and can create an instance of Class entityType from it.
So with all of that explained, what exactly is going wrong in your approach? Well, the issue is that the default implementations available to your JAX-RS runtime probably don't have a writer specifically for an input of type JsonObject and with expected output application/json. It may seem very logical if the server expects JSON, that you should be able to supply a JsonObject as payload. But if the JAX-RS implementation can't find something to handle that class, then at best it can just use some default approach. In that case it may try to interpret the object as a POJO and serialize it to JSON in a default manner, which could lead to weirdness like this:
{
"valueMap": {
"ip": {
"value": "10.197.70.16"
},
"partNumber": {
"num": 202067,
"integral": TRUE
},
...
}
}
That's what a literal interpretation of the JsonObject instance could look like, depending on which implementation it uses and what is used by JAX-RS to turn it into JSON output. Of course it's possible that the object can't be serialized to JSON at all, either because no suitable MessageBodyWriter can be found or it runs into an error when creating the output.
A first solution would be a very simple one. Just turn the JsonObject into a String and simply provide that as the entity:
StringWriter stringWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(stringWriter);) {
jsonWriter.writeObject(jsonObject);
} // some error handling would be needed here
String jsonPayload = stringWriter.toString();
response = invocationBuilder.post(Entity.json(jsonPayload));
It seems you had already tried that. A possible problem with this is that the MessageBodyWriter that gets used needs to just output the String's bytes in a suitable encoding (probably UTF-8) when presented with a String as output and application/json as the required content type. Some may not do that. You could try Entity.entity(jsonPayload, MediaType.TEXT_PLAIN_TYPE.withCharset("UTF-8")) but then the server might reject the call.
Other possible solutions are
Writing your own MessageBodyWriter for String objects with an #javax.ws.rs.Produces(MediaType.APPLICATION_JSON) annotation on it.
Better yet, writing such a class that accepts JsonObject instances.
Creating POJO classes for your JSON structure and letting those get used for generating JSON from instances or deserializing JSON responses to instances.
Finding an extension library that contains suitable providers for dealing with javax.json classes.
The addition of the com.owlike:genson dependency to your project is exactly the application of that last suggestion. The Genson library provides conversions between Java objects and JSON in both directions, as well as data binding. Part of its code base is dedicated to JAX-RS providers, among which a class suitable for accepting JsonObject as input.
Issue is resolved after adding below dependency. At this point I am not sure on what does it do.
Thanks to Swamy (TCS) for his support to resolve this.
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>1.4</version>
</dependency>
Example using genson
String serialize = new Genson().serialize(
Json.createObjectBuilder()
.add("ip", "10.197.70.16")
.add("partNumber", 202067)
.add("model", "IBM P7")
.build()
);
response = invocationBuilder.post(Entity.json(serialize));

Need a JSON parser for Unity3d

I need to deserialize some JSON objects. I tried to use Tiny-json library, but it's too slow. I tried to use Newtonsoft.Json, but it fails in webplayer with this error:
MissingMethodException: Method not found: 'System.Collections.ObjectModel.KeyedCollection.
What JSON parser do you recommend?
You can try one of these open source solutions:
https://github.com/jacobdufault/fullserializer
https://github.com/mtschoen/JSONObject (https://www.assetstore.unity3d.com/en/#!/content/710) I am using this one most of the times, it's versbose but does its job well, not sure about performance however
Or go with paid ones:
https://www.assetstore.unity3d.com/en/#!/content/11347
Unity 5.3 added Native support of Json Serializer. It is faster than others.
JsonUtility.ToJson to convert a class to Json.
JsonUtility.FromJson to convert Json back to class.
For complete example and information regarding json arrays, see
Serialize and Deserialize Json and Json Array in Unity

Grails - Error saving JSONObject to MongoDB

I am having trouble saving a JSONObject to a MongoDB database using the MongoDB plugin.
I receive the message:
Can't find a codec for class org.codehaus.groovy.grails.web.json.JSONObject..
This is very frustrating because I am using the JSON parser to load JSON data but can't persist this JSON data to the MongoDb which should be straightforward.
Is there a built in way to convert a JSONOBject to a normal Map? I've tried casting it using asType( Map ), ( Map ), and even using toString() and thent rying to convert back from string to object. I've seen that other vanilla Java questions involve using Jackson but I'm hoping there is a Groovier way to do this rather than importing a whole new library for just two lines of code.
This is what I'm doing for now:
Converting the JSONObject to a string and then using com.mongodb.util.JSON.parse() to convert that string to a DBObject that Mongo can use.
It's not the best but it works for now.
I'm not going to accept this answer because I don't think it's the right answer.
Not saying this is the correct answer, but I was able to convert the JSONObject to a HashMap. For my situation I had a Domain object with an ArrayList (converted from JSONArray by a previous JSONTranslationService) and I was able to convert each of the internal JSONObjects using something like this:
static final UNMARSHAL = { thing ->
thing.objects.collect {
it as Hashmap
}
}
I'm only experiencing this issue after an upgrade from mongodb:3.0.2 to 6.1.2 to support MongoDB 3.4. Are you also running this version of the plugin? If so, I think it's fair to say that there's either a bug in the plugin (I'm already aware of one) or something changed with the default behavior and wasn't documented.

Problem using lift-json and play framework to parse/extract json objects

I would like to use Lift-JSON (v2.2) with Play framework to parse a JSON file into Scala case classes. I am using scala 2.8.1 and play 1.1 with scala pluging v0.8. To start I copied the code from https://github.com/lift/lift/tree/master/framework/lift-base/lift-json/ for extracting value into classes (Person class, section "Extracting values". When I browse to localhost to see the results I receive
play.exceptions.JavaExecutionException: Parsed JSON values do not match with class constructor
args=
arg types=
constructor=public controllers.Person(java.lang.String,controllers.Address,scala.collection.immutable.List)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:285)
at Invocation.HTTP Request(Play!)
Caused by: net.liftweb.json.MappingException: Parsed JSON values do not match with class constructor
args=
arg types=
constructor=public controllers.Person(java.lang.String,controllers.Address,scala.collection.immutable.List)
at net.liftweb.json.Meta$.fail(Meta.scala:128)
...
I suppose Play somehow runs scala commands in REPL mode ( the problem discussed here: http://caffiendfrog.blogspot.com/2010/11/scala-json-lift-web-trouble-with.html ). I appreciate your experience with using play and lift-json to parse/extract json objects.
I switched from lift-json to https://github.com/codahale/jerkson , problem resolved.
You should look another discussion about this problem, it seems to be explained :)