How to convert a string response to a object using feign decoder - jackson

I am new to feign. I have a feign client for a token end point. Apparently we are hitting the /token end point to get the a json string {"token" : "xxxxyyyxxx", "scope": "EPServices","expires-in": "3600"}. I have a pojo class to map these attributes.I want to use feign decoder to do that. How do I do that. The return type of my feign client method is String.

If you already have a pojo class eg. TokenResponse then you directly use it on the feign interface and it will automatically be deserialized into the POJO for you, since Feign has internal decoders to do that for you automatically.
#FeignClient()
public interface TokenClient {
#GetMapping(path = "/token")
TokenResponse getToken();
}
After you get a TokenResponse you can use a Jackson object mapper or GsonDecoder to convert it to json string if you'd like in another class.
But if you want this all done automatically simply change to this
#FeignClient()
public interface TokenClient {
#GetMapping(path = "/token")
String getToken();
}
and it will be deserialized for you as a json in String.

Related

How to implement Custom Deserializer

I have written a custom serializer and attached it to my RestClient. I am trying to also implement a custom deserializer as well. I noticed in my code that the serializer gets called when i added it to my client like so :RestClient Client = new RestClient(options).UseSerializer<CustomJsonSerializer>();
However, I am not sure what code to add to point to my custom deserializer and where to add it.
I am trying to call a method that essentially hijack's the response content, changes the string, and then sends the modified string back as the new response content to then be deserialized.
Where would i add the code to call my custom deserializer? What would the code snippet look like? And is it possible to even alter the response.content before the deserialization happens? And if so, how do i implement that?
The UseSerializer<T> expects T to be IRestSerializer, which has properties for ISerializer and IDeserializer. The Deserializer property needs to return your custom deserializer.
public interface IRestSerializer {
ISerializer Serializer { get; }
IDeserializer Deserializer { get; }
...

How to make Jersey / Moxy more restrictive when unmarshaling JSON?

I'm currently using Jersey and Moxy in Glassfish 4. Is there a way to tell Jersey/Moxy to refuse a HTTP request if its JSON content is not valid (i.e. it contains more objects than it should when binding JSON to a POJO) ?
I would create my own subclass of MOXyJsonProvider (see: http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html). Then in that subclass I would override the preReadFrom method. In that method I would set an Unmarshaller.Listener.
#Override
protected void preReadFrom(Class<Object> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
Unmarshaller unmarshaller) throws JAXBException {
Unmarshaller.Listener ul = new YourUnmarshallerListener();
unmarshaller.setListener(ul);
}
Then Unmarshaller.Listener would then count each time an object was unmarshalled and error out if too many are read.

WCF Polymorphism in service contract

I am trying to create a service that with an operation that accepts, as a parameter, an any object that implements a specific interface. I would have thought this would be easy to accomplish, but I am running into problems (what I am guessing to be serialization problems but I am not certain). I have the following contract:
//Unsustainable because I would need a method for each of the (currently)
//3 student types, plus I have 2 more root categories that have multiple subtypes
public interface IEmailTemplateAccess
{
[FaultContract(typeof(ValidationFault))]
[FaultContract(typeof(ErrorResponse))]
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
TemplateResponse GetStudentTemplate(ITemplateRequest request);
}
And this is what I would like it to look like:
public interface IEmailTemplateAccess
{
[FaultContract(typeof(ValidationFault))]
[FaultContract(typeof(ErrorResponse))]
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
TemplateResponse GetTemplate(ITemplateRequest request);
}
In my service I use an abstract factory to return the correct template based on the type of request that comes in. In addition, I have created concrete ITemplateRequests for the different kinds of templates that could be returned. For example, I have Template Request types A and B. Template Request Type A can have one of 3 sub types, SubType1, SubType2 and SubType3. I then created a SubType3 request that implemented the ITemplateRequest interface (SubType3Request).
I would hate to have to create a method for each request type I have (i.e. GetSubType1Template, GetSubType2Template, GetSubType3Template, GetTypeBTemplate, etc) as this would quickly become unwieldy as the types of templates I can get will be changing occasionally.
Is there a way to have a contract method accept anything that implements ITemplateRequest as a parameter and let my factory do the work of figuring out what type of template to get?
So far, I have the following methods in my service:
//Not a part of the contract right now although I would like it to be
public IEmailTemplate GetTemplate(ITemplateRequest request)
{
TemplateFactoryBuilder builder = new TemplateFactoryBuilder();
ITemplateFactory factory = builder.GetTemplateFactory(request.Type);
var template = factory.GetTemplate(request);
return template;
}
//contract method --This would be my Parent Request Type (RequestTypeA) from above.
//There are 3 subtypes of the Student type
public TemplateResponse GetStudentTemplate(StudentEmailTemplateRequest request)
{
var response = new TemplateResponse
{
RequiresProcessing = true
};
response.Template = (EmailMergeTemplate) GetTemplate(request);
return response;
}
Sorry for the link-ish answer, but it's pretty long.. What you're after (I think) is here: http://blogs.msdn.com/b/morgan/archive/2009/08/05/polymorphism-in-wcf.aspx
It boils down to using known types. Something like this;
[ServiceContract]
[ServiceKnownType("GetKnownTypes", typeof(CommandServiceHelper))]
public interface ICommandService

Cannot deserialize with XMLSerializer result from WCF webservice

Here is the code trying from compact framework to get http service..
List<Table> tables;
using (Stream r = response.GetResponseStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(Table),"http://schemas.datacontract.org/2004/07/");
tables=(List<Table>) serializer.Deserialize(r);
}
response.Close();
It fails with {"There is an error in XML document (1, 2)."}
{"<ArrayOfTable xmlns='http://schemas.datacontract.org/2004/07/WpfApplication1.Data.Model'> was not expected."}
Table namespace is the same...
I dont know whats wrong there...
UPDATE
Problem was that i had typeof(Table) not typeof(List<Table>) which works partially.. No error but created tables values are null!
The second parameter on the XmlSerializer constructor works for both serializing and deserializing. So, on the second parameter (the namespace) should be the same to the one being received. So you'll end up having:
XmlSerializer serializer = new XmlSerializer(typeof(Table),"http://schemas.datacontract.org/2004/07/WpfApplication1.Data.Model")
Note the "WpfApplication1.Data.Model" at the end of the namespace string.
One way to get rid of the namespace thing. Is to specify on your model class (Table) that it should not use a namespace:
[DataContract(Namespace = "")]
public class Table { ... }
That way you don't need to specify the namespace for deserialization.
Hope it helps!
Not sure if this will help, but we had a similar issue. Instead of decorating thousands of data elements with DataContract/DataMember attributes and using the (default) DataContractSerializer, we found that if our WCF service used the XmlSerializerFormat instead, we could easily deserialize our objects.
[System.ServiceModel.ServiceContract]
public interface IRestService
{
[System.ServiceModel.OperationContract]
// Added this attribute to use XmlSerializer instead of DataContractSerializer
[System.ServiceModel.XmlSerializerFormat(
Style=System.ServiceModel.OperationFormatStyle.Document)]
[System.ServiceModel.Web.WebGet(
ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Xml,
UriTemplate = "xml/objects/{myObjectIdentifier}")]
MyObject GetMyObject(int myObjectIdentifier);
}
This is how we're deserializing the objects:
public static T DeserializeTypedObjectFromXmlString<T>(string input)
{
T result;
try
{
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (System.IO.TextReader textReader = new System.IO.StringReader(input))
{
result = (T)xs.Deserialize(textReader);
}
}
catch
{
throw;
}
return result;
}
Instead of returning a List return an object that has a single property of List.

How can I return json from my WCF rest service (.NET 4), using Json.Net, without it being a string, wrapped in quotes?

UPDATE 10/19/2010
I know I asked this question a while ago, but the workarounds shown in these answers are hardly satisfactory, and this is still a common problem for many. WCF just isn't flexible. I started my own open source C# library for creating REST services without WCF. Check restcake.net or rest.codeplex.com for info on said library.
END UPDATE
UPDATE 8/2/2012
ASP.NET Web API (previously WCF Web API, the replacement for REST WCF) uses Json.NET by default
END UPDATE
The DataContractJsonSerializer is unable to handle many scenarios that Json.Net handles just fine when properly configured (specifically, cycles).
A service method can either return a specific object type (in this case a DTO), in which case the DataContractJsonSerializer will be used, or I can have the method return a string, and do the serialization myself with Json.Net. The problem is that when I return a json string as opposed to an object, the json that is sent to the client is wrapped in quotes.
Using DataContractJsonSerializer, returning a specific object type, the response is:
{"Message":"Hello World"}
Using Json.Net to return a json string, the response is:
"{\"Message\":\"Hello World\"}"
I do not want to have to eval() or JSON.parse() the result on the client, which is what I would have to do if the json comes back as a string, wrapped in quotes. I realize that the behavior is correct; it's just not what I want/need. I need the raw json; the behavior when the service method's return type is an object, not a string.
So, how can I have my method return an object type, but not use the DataContractJsonSerializer? How can I tell it to use the Json.Net serializer instead?
Or, is there someway to directly write to the response stream? So I can just return the raw json myself? Without the wrapping quotes?
Here is my contrived example, for reference:
[DataContract]
public class SimpleMessage
{
[DataMember]
public string Message { get; set; }
}
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class PersonService
{
// uses DataContractJsonSerializer
// returns {"Message":"Hello World"}
[WebGet(UriTemplate = "helloObject")]
public SimpleMessage SayHelloObject()
{
return new SimpleMessage("Hello World");
}
// uses Json.Net serialization, to return a json string
// returns "{\"Message\":\"Hello World\"}"
[WebGet(UriTemplate = "helloString")]
public string SayHelloString()
{
SimpleMessage message = new SimpleMessage() { Message = "Hello World" };
string json = JsonConvert.Serialize(message);
return json;
}
// I need a mix of the two. Return an object type, but use the Json.Net serializer.
}
I finally figured out a solution to this. It's not what I would have preferred (which would be to return the specific object type, and somehow instruct WCF to use a Json.Net serializer, instead of the DataContractJsonSerializer), but it is working great, and it's simple and clear.
Extending my contrived example using this new solution:
[WebGet(UriTemplate = "hello")]
public void SayHello()
{
SimpleMessage message = new SimpleMessage() {Message = "Hello World"};
string json = JsonConvert.Serialize(message);
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.Write(json);
}
Note the return type of void. We do not return anything, since it would be serialized with DataContractJsonSerializer. Instead, I write directly to the response output stream. Since the return type is void, the processing pipeline doesn't set the content-type to the default type of "application/json", so I set it explicitly.
Because this uses HttpContext, I'm guessing it will only work if you have [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] on your service class, since that will force requests to the service to go through the ASP.NET pipeline. Without the asp.net compatibility, the HttpContext will not be available, since wcf hosting is supposed to be host agnostic.
Using this method, the results look perfect in firebug for GET requests. Correct content-type, correct content length, and raw json, not wrapped in quotes. And, I'm getting the serialization I want using Json.Net. Best of both worlds.
I'm not 100% positive of what obstacles I might run into regarding deserialization, when my service methods have [DataContract] object types as input parameters. I'm assuming the DataContractJsonSerializer will be used for that too. Will cross that bridge when I come to it...if it creates a problem. It hasn't so far, with my simple DTOs.
UPDATE
See Oleg's answer (the UPDATE2 part). He changes the return type of the service method from void to System.ServiceModel.Channels.Message, and rather than using HttpContext.Current.Response.Write(), he uses:
return WebOperationContext.Current.CreateTextResponse (json,
"application/json; charset=utf-8", Encoding.UTF8);
Which is indeed a better solution. Thank you Oleg.
UPDATE 2
There is yet another way of accomplishing this. Change your service's return type from Message to Stream, and return this:
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
I haven't done any specific tests, but it's possible that this would be a better choice for methods that could potentially return large amounts of data. I don't know if that matters for non-binary data though. Anyway, a thought.
It seems to me that you use not correct DataContractJsonSerializer. What is strange is: you don't define ResponseFormat = ResponseFormat.Json attribute for the public SimpleMessage SayHelloObject() method.
Moreover if you have {"Message":"Hello World"} in a string and display it in debugger it will be display as "{\"Message\":\"Hello World\"}", so exactly like you see string json = JsonConvert.Serialize(message); (Json.Net). So it seems to me that you have in both cases the same results.
To verify this use a client software which read the results. See some examples
JQuery ajax call to httpget webmethod (c#) not working
Can I return JSON from an .asmx Web Service if the ContentType is not JSON?
How do I build a JSON object to send to an AJAX WebService?
UPDATED: In your code you define method SayHelloString(). It's result are a string. If you call the method this string will be one more time JSON serialized. JSON serialization of the string {"Message":"Hello World"} is a quoted string (see http://www.json.org/ definition for not a object, but a string) or exactly string "{\"Message\":\"Hello World\"}". So everything is correct with both methods of your Web Service.
UPDATED 2: I am glad that my tip from "Update" part of my answer helped you to swich of the double JSON serialization.
Nevertheless I would recommend you to change a little the solution to stay more at the WCF concept.
If you want implement a custom encoding of the web responce in WCF (see http://msdn.microsoft.com/en-us/library/ms734675.aspx) your WCF method should better return Message instead of void:
[WebGet(UriTemplate = "hello")]
public Message SayHello()
{
SimpleMessage message = new SimpleMessage() {Message = "Hello World"};
string myResponseBody = JsonConvert.Serialize(message);
return WebOperationContext.Current.CreateTextResponse (myResponseBody,
"application/json; charset=utf-8",
Encoding.UTF8);
}
You can of cause use another Message formater: for example CreateStreamResponse (or some other see http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext_methods(v=VS.100).aspx) instead of CreateTextResponse.
If you want to set some additional HTTP headers or Http status code (for example in case of some error) you can do this with this way:
OutgoingWebResponseContext ctx = WebOperationContext.Current.OutgoingResponse;
ctx.StatusCode = HttpStatusCode.BadRequest;
At the end I want repeat my question from a comment: could you explain why you want use Json.Net instead of DataContractJsonSerializer? Is it performance improvement? Do you need implement serialization of some data types like DateTime in other way as DataContractJsonSerializer do? Or the main reason of your choose of Json.Net is some other?