java json controller - java

I have an Java class, like Library, that contains many fields. I want do ajax call to server
and in controller's method I want to have partly initialized #RequestBody Library with only
fields, which are present in json object.
I read the http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/, but I need not full object.
Please Help

You could use a org.codehaus.jettison.json.JSONObject (part of the Jettison project) and only include the fields that you need.
Or, you could just make a simplified version of Library that includes only the fields that you want (call it AjaxLibrary or something).

It would not be a problem to use full object, cause fields would not be initialized, if they are not present at entire json.
Also you can create own DTO class, e.g. SomeActionLibraryDTO. Extract required fields from Library, and use #JsonIgnoreProperties(ignoreUnknown = true) annotation for class to ignore the rest of json object (I suppose you are using the default json jackson marshaller, right?)

Related

How to create a field of data type varchar in controller class

How do I create a field of data type varchar in my controller class with size as 20?
Also, could anyone please tell me how to create a field of data type none. Also, how to mention the fields to be mandatory?
I am quite beginner in this. Any help would be appreciated.
you cannot declare varchar in controller you have to use String
private String str = ""; or you can use this
StringBuilder str
= new StringBuilder();
str.setLength(20);
Ok, so your question is lacking context so I am going to make some assumptions. I'm assuming that you have to implement some controller that exposes an URL endpoint. I assume that you want to be able to receive data on that endpoint and map it to an object (dto). I assume that you want to assure that you want to perform validitions on the received data.
Im on my phone so I won't write it out completely but let me give you some pointers.
Create a dto object with the data structure that you're expecting to receive.
Create a contreoller with #Controller annotation.
Within the controller, create a method with the #postMapping annotation and configure it appropriately. The method should accept the dto class and a binding result class as method parameter. Within the method definition use the #Valid annotation before the dto class. The informs Spring to validate the dto and it will inject the valdition result into the Binding Result object. Note that the latter should be mentioned after the dto, in this example it would be the second and last parameter.
Now in the dto, you can annotate the class fields with annotations from the javax.validation package. For example #NotNull or #Size which could assert the size of a string field and assure the availability of a field value. Note that I believe in later versions of Java, the validation package was moved to Jakarta package so take that into consideration. Also make sure to use the right annotations, for example there is also #Nonnull from spring which does other stuff.
Now, within the method body you can now assert if there where any binding result errors. Just check the BindingResult.hasErrors() and then handle them appropriately.
The field of data type None does not ammake sense to me so will need more information to be able to help with that.

Java JSON deserialization without predefining everything

I realize this has probably been asked a hundred times but I have searched a lot and can't find specifically what I'm looking for.
Here is what I'd like. Given a string data, I'd like to deserialize into an object obj that doesn't have all the fields predefined. I'd like to just be able to ask for the fields I want such as obj.getString("stringFieldName") or obj.getInt("intFieldName"). I already have gson being used for other things so if it is possible with gson that would be great although not opposed to using another library.
The 'standard' Android JSON library (since API 1) already provides such untyped access.
See JSONObject, eg. getInt:
Returns the value mapped by name if it exists and is an int or can be coerced to an int, or throws otherwise.
Unless needing the JSON mapped onto a 'native' Java collection type this is probably the simplest way to achieve the request. It doesn't require any additional libraries.
With Jackson library you can annotate data model class with
#JsonIgnoreProperties(ignoreUnknown = true)
and the jacksonconverter will just parse only these fields that you defined. Other will be ignored.
Have you tried using Retrofit from Square? It works with GSON and Java Annotations and it's super easy to set up.

simple method/extendable class to make my toString method of a POJO output json like output?

I have a number of pojos which are being used for a jersey client to be filled with the JSON data from a restful call. The client is reading in json and filling these objects using the JacksonJsonProvider. I'm not using any annotations, the variable names are equal to the json coming in.
I would like the toStrng methods for these PoJos to automatically output a representation of the json they represent, without my having to manually write each toString. Since these are basic POJO which are structured in a simlpe tree format it should be realatively easy to output these pojo as json in the toString method. In fact I know I could use reflection to do this myself in some parent/abstract class if I felt like it. However, it feels like I shouldn't have to do this by hand. Is there already some method out there that will do this for me I can use instead?
I don't insist that the output be json, though that would be preferable, but any similar method of visualizing the variables automatically without my manually writing it would be fine.
Thanks
If you use Google GSON you can serialize objects into JSON. Your toString() would then look something like:
public String toString() {
return StaticLib.GSON.toJson(this);
}
A GSON object can be shared across all objects, hence my inclusion of this mystery StaticLib class. You can find the correct name or place for that in your own project I'm sure.

Using polymorphism at deserialization time with Jackson (and MrBean)

I'm using Jackson to deserialize some JSON into Java POJOs. I register the MrBean module with my object mapper, so all I have to do is define a bunch of interfaces, and the POJOs are generated automagically, based on those interfaces.
I would like to have a Credentials interface with various types of credentials that extend it, e.g. UsernamePasswordCredentials and CertificateFileCredentials.
Doing this without any annotations or other incantations to try to make it work gives me the following error in my unit test:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "username" (Class org.codehaus.jackson.generated.SCRUBBED.Credentials), not marked as ignorable
at [Source: java.io.StringReader#e0b6f5; line: 32, column: 29] (through reference chain: HostConfiguration["hostDefinitions"]->HostDefinition["credentials"]->Credentials["username"])
I've also followed the instructions at another StackOverflow post, and I'm getting the same error.
The error makes sense; Jackson is trying to map the contents of my JSON file to an empty interface. However, I (naively, perhaps) expected Jackson to look for interfaces that extend the base Credentials interface and try to match up the fields in those interfaces to the fields it found in the JSON object.
I've seen some examples at the Jackson wiki that make use of meta-information in the JSON object, e.g. decorating an object with "#class":"foo.bar.CertificateFileCredentials", but I'd prefer to avoid any of that since my JSON input will be generated automatically by other services, and those other services shouldn't have to know anything about the internals of my service.
Thanks!
How would you define actual implementation classes? As additional interfaces? Those should get generated correctly; but the problem is during deserialization: there must be some way for deserializer to find out actual type to use, if there are multiple choices.
For this, #JsonTypeInfo is recommended to be used as you have noticed.
Actually, the technique would work well for your purposes too, even though you don't control the service that generates the JSON.
Saving the class name is a nice easy default when using #JsonTypeInfo but Jackson lets you customize this to your liking.
For example, suppose the service generates JSON that looks like this:
{ meows: 400, furColor: "green", species: "cat" }
Then you can define these interfaces to convert it properly.
#JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY,property="species")
#JsonSubTypes({
#JsonSubTypes.Type(value=Feline.class, name="cat")
})
public interface Animal {
public String getFurColor();
}
#JsonTypeName("cat")
public interface Feline extends Animal {
#JsonProperty("meows") // just to have an example of a renamed property...
public long getMeowingVolumeInDecibels();
}
Then you should just automatically get the right java type at runtime when deserializing, as well as automatically generate the "species" property depending on the runtime type. Hope that helps!

Map JSON Response to POJO (with different names)

I know there are numerous posts out there for a similar problem, but mine seems to be a bit different. I am reading in a bunch of JSON and would like to build POJO from it, but I don't want to use the names of the JSON result. Is there a way to "map" the element names in JSON to the attributes in my POJOs (using gson or Jackson maybe)?
It's worth mentioning this application is being built for Android.
Thanks in advance!
If you're using Gson, you can append an attribute to your objects, like so:
#SerializedName("ServicesResult")
public String services;
Where "ServicesResult" is the actual name of the element in the JSON.
With Jackson, you have multiple options:
Use #JsonProperty("name") annotation to indicate name to use in JSON, add directly or use mix-in annotations (external)
Specify PropertyNamingStrategy to convert from "Java name" to "JSON name" (there is default java<->c-style converter bundled with 1.9)
Modify AnnotationIntrospector to change the name using some other mechanism than annotations
Jackson will also interpret the Basic package javax.xml.bind.annotation
If you use those annotations you can readily move between Json/XML

Categories

Resources