Changing Field Name Value in ViewModel - json

Is there any way to change the FieldName Value for a property in a Viewmodel? I would like to use the standard naming convention for the property, but have the viewmodel return something else. This is important, because I have a json request that requires the properties to be in lowercase.
I have tried using both XMLAttributes, and DataMembers, but neither of those soultions worked. Those came from the following questions.
Serialize .Net object to json, controlled using xml attributes
JavaScriptSerializer.Deserialize - how to change field names
So, to reiterate, I need something like this
public string Start { get; set; }
to show up as
viewmodel.start
instead of
viewmodel.Start
when I am passing my viewmodel to the callback inside the getJson request

What about adding an extra property to your model?
public string start {get {return Start;}}

Related

How to read step method contents from allure listener

Currently, I am using allure StepLifecycleListener to listen to #step. I want to get some parameters inside the method.
For Eg : I want to get
"RequestIdentifier.userservice_CreateLogin" parameter in below
#Step("Perform user login with retrieved OTP")
public BaseResponseDTO performUserLogin(String deviceId, String authId, String otp) {
response = serviceManager.sendRequest(RequestIdentifier.userservice_CreateLogin, requestParams);
}
I can get String deviceId, String authId, String otp from StepResult getparameters() method, but how can I get some parameters inside the performUserLogin() method.
You can't. Step annotation works with the method's signature, not with its body. If you want to get RequestIdentifier.userservice_CreateLogin value, just overload the method and pass a corresponding value as an argument.
On the other hand, it seems like a public static variable. In this case, you can always explicitly access it from within your AllureStepListener. However, it'd be an ugly approach.
I'd consider redesigning your API the way it'll work with custom types (aka entities) rather than passing raw strings. In this case, you can always compose all the required data (including statics) into your custom entity and then easily access it within Step annotation via "Bla-bla {entity.field}" syntax.

How to modify spring/jackson JSON deserialisation

I'm trying to figure out how to adjust the way spring/jackson convert a JSON string (stored in a file) into various POJOs. For example, if I have this JSON:
{
"rates":{
"EURUSD":5.4321,
"USDHKD":1.2345
}
}
I actually want to get an instance of my 'Rates' class. Inside that I want a List containing each individual rate.
In my spring config file I created this entry:
#Bean
public ObjectMapper jsonObjectMapper() {
return new MappingJackson2HttpMessageConverter().getObjectMapper();
}
And in my service class I did this:
#Autowired
ObjectMapper jsonObjectMapper;
public Rates currentRates() {
Resource resource = this.ctx.getResource("classpath:stub/data/rates/Rates-01.json");
return this.jsonObjectMapper.readValue(resource.getURL(), Rates.class);
}
The problem is that I am trying to figure out how to take the Map containing the currencies as a single key, break those currencies in two and then create a RateEntry object containing the two currencies and the rate, before populating a list in the Rates class.
I've been looking at Spring's Conversion Service with the idea to define a converter that maps the Map to a list. i.e. this signature: Converter<Map<String, BigDecimal>, List<Rate>>. However this is based on the assumption that the JSON is first converted to standard types before the conversion service is called. An assumption I now think is incorrect.
So I'm now trying to figure out if I need to register some sort of custom ObjectMapper to handle reading directly from the JSON String data. But that sounds like over kill as I only want to adjust part of the object graph, and let the default converters handle the rest.
Any pointers appreciated. Thanks.
Ok, Jackson tries to stay away from structural transformations (since it's a quick-sand pit with unlimited number of general permutations). But it might be possible to use some existing features to do what you want.
First: to use Object key to indicate type, you will probably want to enable polymorphic type handling with "as object wrapper" inclusion.
So add something like:
#JsonTypeInfo(as=Include.WRAPPER_OBJECT)
for your Rates class declaration.
As to converting values into list; this might work by defining "any-setter" (see http://www.cowtowncoder.com/blog/archives/2011/07/entry_458.html), something like:
#JsonAnySetter
public void set(String key, Double value) // or "Object value")
{
list.add(new Rate(key, value));
}
I hope this helps.

Java validator for String

How do I validate using Hibernate validator for elements appearing more than once in a JSON payload bound to a Java class annotated with validator annotations?
Let's say I have the following:
class Person {
String name;
int age;
}
I am binding JSON to Person.
The JSON payload looks like the following:
{
"name":"someName",
"age":30
}
Let's say the payload has 2 "name" fields repeated as below.
{
"name":"someName",
"name" : "otherName",
"age":30
}
Then I like to use the validator to validate this. It will work for Collection objects if I use #Size(min=1, max=1).
I am wondering how I make this work for String. With String #Size tries to look for the length of the string content and not the number of times the string content in the payload.
Thanks for your time!
This is not possible. JSON deserialization and Bean validation are two entirely different things. By the time your Hibernate validation kicks in all it sees is a Person object, with a single name field.
It is the behavior of your JSON library that will determine which of the "name" fields will be deserialized into the Java bean (or if an exception will be thrown). For the most part, if you want to validate that no duplicates are supplied then you are going to need to write some custom deserialization code.

WinRT serializing a DateTimeOffset

I'm working on a Windows 8 Metro application that references a c# WinRT project. Among other things, the c# project makes web requests to an Azure service to perform CRUD operations against a SQL Azure database.
When performing a POST operation on the service, I'm serializing an instance of a class and putting it in the body of the request.
public sealed class Foo
{
int FooId { get; set; }
DateTimeOffset FooDate { get; set; }
}
When this is serialized using the DataContractJSONSerializer, the result is something like this:
{"FooId":1,"FooDate":{"DateTime":"/Date(1342732970000)/","OffsetMinutes":-420}}
FYI that this is 7/19/2012 2:22:50PM -07:00.
OK great ... Only problem is that the Azure service is expecting just a DateTime, not a DateTimeOffset. I don't own the Azure service so I can't change its behavior.
So (ignoring that I'm losing the offset) what I need is this to serialize into:
{"FooId":1,"FooDate":"/Date(1342732970)/"}
My first approach was to add a new aliased DateTime property/datamember to the class with a getter that returns the DateTime portion of the DateTimeOffset. However, WinRT doesn't support the DateTime type.
There are a couple of hacky ways to get around this, but I wanted to see if there's an elegant way to do this before resorting to one of these:
Regex on the serialization result before the POST
String property on the class that returns a JSON formatted date
Thanks
I ended up implementing a property on the class with a getter that formats the date appropriately.
I decorated the Foo field with the IgnoreDataMember attribute so that it gets ignored during serialization. I then added a new field and gave it the alias of Foo for serialization.
Thanks

How to serialize transient fields in the model via FlexJson?

I am using Play Framework to expose REST API, which returns some JSON objects.
To simplify the API usage, I would like to return a "calculated" field in the response.
Unfortunately, in my tests, while FlexJson does not ignore the transient model fields completely, but always sets them to 'null'.
More details:
In the model class, I define:
#Transient
public String currencyName;
The only constructor of the class set the value to "dollar" (for debugging purposes):
this.currencyName = "dollar";
When serializing the class using FlexJson, when the 'currencyName' field is not specified in the include/ exclude - the result always looks like:
"currencyName":null
Any idea what got wrong, and how to get the field value serialized into JSON?
Thanks in advance.
By definition if your field is transient it will not be serialized. Perhaps this field should not be transient in your application if the state matters.