I'm currently using RestEasy(2.3.6) with Jackson(1.9.9) and needing to prefix my JSON arrays with '{} &&' in order to prevent JSON hijacking.
I'm new to Jackson and am having a really hard time understanding where to insert anything like this. I'm not even sure where to insert something like this to make it happen all the time, and I would like to take it one step further and be able to specify to only prefix return values that contain JSON arrays and not regular objects.
I imagine there is a class somewhere I need to subclass and override a method, and then register that class somehow. Has anyone ever done anything like this?
Jukka, the question you linked to led me to a solution. I extended JacksonJsonProvider, and overrode the writeTo() method. There are a few conditions in there and I was able to add jg.writeRaw("{}&&"); before each place it writes the value. Also, since I'm using Spring, I had to annotate my class with #Component in order for it to be found.
Also another gotcha with creating your own JsonProvider subclass is your rest methods must have #Produces('application/json') (you should always be explicit with these anyway) or else the default JsonProvider will be used.
Related
In my application I need to use dynamic localization, so I cannot use Constants interface. I did use Constants for a while, but now I need texts to be changed without compiling so I had to find some other way.
So I am using Dictionary now. The thing is, when I now want to use text in UiBinder, I can only use methods without arguments. So I created class "StringIdentifiers" where I have the same methods I previously had in MyConstants, but I have to specify a body here for every method to return the specified String.
So for example I have:
Dictionary locale = Dictionary.getDictionary("myJsObjectWithStrings");
//and then the methods for returning the actual strings from the JS object
String loading(){
return locale.get("loading");
}
I would like the method to only be
String loading();
since the rest is always the same with the name of the method appearing as String parameter in the get() method. Possibly even returning some default value when the String is missing in the JS object. But I do not know how to do that. I checked the Constants interface, but I do not really understand the code there. Can someone please give me an example how to implement such a thing?
There is no standard feature in GWT to do this, but you could create one yourself. It's a bit of a stretch, but it should work by using the GWT generator mechanisch. In global terms it should work as follows:
Create an interface (say MyMessages) with a the method names.
To use it use MyMessages message = GWT.create(MyMessages.class). Where you need the text message.loading().
Create a generator that generates an class implementing the interface. This class will created at compile time and should contain the implementation of the interface methods, like in your example.
Add a generate-with tag in your gwt.xml file to make it work.
This is a bit of a brief explanation, but I hope it helps. For more background information about generators see: What is the use GWT generator? or http://blog.arcbees.com/2015/05/26/how-to-write-gwt-generators-efficiently/
You could even reuse some of GWT's annotation's of the i18n to add for example default texts. Add the annotation to your interface and in the generator scan the annotation and use it in the code generation part.
As you could see from this question, the response that worldweather return is not quite pretty. They return array of current weather conditions (I try to understand why did they made it that way, there couldn't be more then one weather condition in a specific place, as far as I know...), so it breaks the unmarshalling via annotations,
#JsonProperty("current_condition")
private CurrentWeatherData currentWeatherData;
because Jackson actually awaits a collection or an array. Now, can I somehow to tell the unmarshaller to use the first array member, and if yes, how do I do that?
There is no such annotation. You will probably want a custom deserializer to handle this special case.
For Jackson 2.2 there will be support for separate Converters, which could work here (as they only work on Java objects). But since it is not yet released, custom deserializer is probably the way to go.
I have a java class, for some field (not all field), I will put an annotation for the filed. Now, I would like to find all the fields which have annotation?
I know, I can iterate all fields, and find whether the field has annotation.
Since there is only one or two field has annotation, so I would like a quick method to find such annotated field.
I don't know any way quicker than iterating over all the fields. Given that anything else would require some other piece of code to iterate over all the fields first and store the annotations in a form more optimized for your use case - which certainly won't be useful for all annotations - I wouldn't expect there to be anything provided for you.
Have you benchmarked the speed of just iterating over the fields, and found it too slow? If you only need to do this occasionally, it's probably fast enough as it is. If you need to do it multiple times on the same class, then you can create a cache for this yourself, so you only ever need to iterate over the fields of any particular class once.
I have been using the jackson implementation of the json protocol in my own little project, and it has gone just fine a while now until I decided (for the first time) to serialize a stateless object.
I know that might sound weird, why would I want to send a stateless object? What I serialize is requests for a server, and this particular one conatins no fields, just code for an instruction on the server side. My model can take any ClientRequest implementation and call it's perform() method. I want it to work even though the request comes without fields.
Code looks like this:
public class GetWallInputsRequest implements ClientRequest<List<WallInput>>
{
#JsonCreator public GetWallInputsRequest()
{
}
#Override public ServerResponse<List<WallInput>> perform()
{
return new WallMessageResponse( Wall.WALL.getInputs() );
}
}
I get JsonMappingException: No serializer found for class GetWallInputsRequest.
Google does not help me, which makes me wonder if I'm just being stupid. Sadly I don't see a way out of this.
I solved it after a lot of brute force attempting different things. And by solved it I mean not figured it out but made it work. By adding the line:
#JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE)
above the class declaration it seems to work out. Why this is necessary I don't know, but now It sends an empty json string instead of crashing.
The documentation says
Value that indicates that no access modifiers are auto-detectable: this can be used to explicitly disable auto-detection for specified types.
Since your class doesn't include any explicit notations to tell Jackson that there's a field or method to serialize, it determines that there is indeed nothing to look for. Without this, I presume, it's going to expect something, as suggested in the documentation quoted.
http://jackson.codehaus.org/1.9.0/javadoc/org/codehaus/jackson/annotate/JsonAutoDetect.Visibility.html
I have an application that saves its context to XML. In this application, there is a hierarchy of classes, that all implement a common interface, and that represent different settings. For instance, a first setting class may be made of 4 public float fields, another one can be made of a sole HashMap.
I am trying to determine what is the best way to handle writing and reading to XML in a generic way. I read on this site a lot about JAXB and XStream for instance, which are able to make a specific class instance from XML.
However my question is related to the fact that the actual class can be anything that implement a given interface. When you read the XML file, how would you guess the actual class to instantiate from the XML data? How do you do that in your applications?
I thought that I could write the .class name in a XML attribute, read it and compare it to all possible class .class names, until I find a match. Is there a more sensible way?
Thanks
xstream should already take care of this and create the object of correct type.
The tutorial seems to confirm that:
To reconstruct an object, purely from the XML:
Person newJoe = (Person)xstream.fromXML(xml);
If you don't know the type, you will have to first assign it to the common interface type:
CommonInterface newObject = (CommonInterface)xstream.fromXML(xml);
// now you can either check its type or call virtual methods
In my case I just have a kind of header that stores the class name that is serialized and when de-serializing it I just use the header value to figure out to which class shall I de-serialize the values.
A best practice would to use an established, well documented XML parser/mapper. All of the serialization/deserialization work has been done, so you can worry about your business logic instead. Castor and Apache Axiom are two APIs that I have used to marshal/unmarshall(serialize/deserialize) Java Classes and XML.
http://www.castor.org
Apache Axiom