Is it possible to deserialize a JSON string to an object without using the DataContractJsonSerializer in System.ServiceModel.Web? I have the following code but I need a payed license to use it...
response = (HttpWebResponse)request.EndGetResponse(iar);
System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Result));
Result result = (Result)ser.ReadObject(response.GetResponseStream());
I'm using RestSharp to consume my Web.API service that sends data via JSON. However, I'm using JSON.NET to deserialize it.
_client.ExecuteAsync (request, (response) => {
List<Account> data = JsonConvert.DeserializeObject<List<Account>>(response.Content);
This works just fine for me and JSON.NET is free, very quick, and kind of the de facto JSON serialization library for .NET.
http://james.newtonking.com/projects/json-net.aspx
Related
I am trying to enable web api to support both JSON and XML as return type. While serializing complex datattype to XML I got circular reference errors, so I decorated my main class with DataContract(IsReference = true), now XML serialization is working and json serialization not working.
thanks in advance.
PS: i am able to serialize simple dto classes to both xml and json, but for complex datatypes the problem is coming.
Set the followings in App_Start/WebApiConfig.cs
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());
Set application/json or application/xml to Accept header in request-side.
Result will be decided based on result type formatter. Hence I wrote 2 different methods for each return type. To solve, circular reference errors while generating xml i followed below steps.
Serialize class result
Deserialize class result.
Write it to xml.
var json = JsonConvert.SerializeObject(result);
var rO = JsonConvert.DeserializeObject<TClass>(json);
return Ok(ReturnAsXml(rO), Configuration.Formatters.XmlFormatter);
protected virtual XElement ReturnAsXml<T>(T data)
{
Type t = data.GetType();
DataContractSerializer serializer = new DataContractSerializer(t);//, extraTypes);
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
serializer.WriteObject(xw, data);
var o = XElement.Parse(sw.ToString());
return o;
}
My wcf project returns the Countries List as json, in wcf project parse using Newtonsoft json. I get json in my client website built on mvc, i show the data using jtable plugin in jquery. The plugin failed to display because, the json contains /(back slashes).
Code to display jtable is
Name:{
title: 'Country Name',
width: '40%',
options: '/Country/Index'
}
Country/Index result is
{"Result":"OK","Options":"[{\"DisplayText\":\"India\",\"Value\":1},{\"DisplayText\":\"Singapore\",\"Value\":2}]"}
Country/Index gets the result from wcf service. Is there any way to strip the / in json.
Edit:
My wcf code is
List<JSONDisplayNameValue> lstLanguages = new List<JSONDisplayNameValue>();
//Get data from db.
//JSONDisplayNameValue has two variables DisplayName, Value
var json = JsonConvert.SerializeObject(lstLanguages);
return json;
Country/Index mvc code is
public JsonResult Index()
{
string Countries_list = processsvc.GetAllCountries();
return Json(new { Result = "OK", Options = Countries_list }, JsonRequestBehavior.AllowGet);
}
You are getting backslashes because you are double-serializing your data.
In your WCF code, you call JsonConvert.SerializeObject() to serialize your list of countries/languages to JSON before returning it.
In your MVC controller, you call your WCF service to get the list, which is already in JSON format. But then you add that JSON to another object and call Json() which causes the list to be serialized a second time. That is where the backslashes get added.
To fix this, you either need to
Deserialize the list you get back from your WCF service before adding it to the MVC result.
-- OR --
Make a way to retrieve your list of countries/languages without serializing it to JSON. Then add the unserialized list to your MVC result and serialize it as normal.
I have started to learn about REST API. So far I have been able to call my REST API post data using the form and also to get values from my REST API. Now I am trying to learn to send my data to my REST API using JSON object. I have been searching on the net and reading on StackOverflow on how to implement it but so far there is no luck. I am looking for some basic code examples where I can get an idea of how it's done. If some could help me with some codes on how to send data to my REST API using JSON and also how to retrieve that JSON data in my REST API it will be very helpful to me in learning REST API(Just the basic codes I hope it shouldn't take much of your time to post some codes). Btw I am using Jersey to implement my REST API. Thanks in Advance :) It really will be helpful to me in understanding sending JSON data to my web service Thanks again :)
The language is JAVA(JAX-RS implemented in Jersey)
While sending data in json request, your request should be in the form of a map (key value pair ). Key should be your attribute name and values as the value for the attribute.
For example if you are trying to find a employee using employeeid the your request should be of the form {data:{"employeeid":"1"}}
Be more specif about which platform you are using to call the RESTservice.
Hope this will help you.
var clientCreateOrder = new RestClient("#######################");
var requestCreateOrder = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
//Use below code for creating and sending dynamic json objects to RESTAPI
object[] purchase_units_arr = new object[1];
purchase_units_arr[0] = new
{
amount = new
{
currency_code = "USD",
value = "100.00"
}
};
var body = new
{
intent = "CAPTURE",
purchase_units = purchase_units_arr,
};
//Serialize Json object
request.AddParameter("undefined", new JavaScriptSerializer().Serialize(body).ToString(), ParameterType.RequestBody);
IRestResponse responseCreateOrder = client.Execute(request);
I'm using RestSharp, and using Json.NET for serialization (see here).
Json.NET supports BSON, and since some of my requests have huge blocks of binary data, I think this would speed up my application dramatically. However, as far as I can tell, RestSharp does not seem to have any in-built support for BSON.
The use of Json.NET is implemented as a custom serializer for RestSharp, and so at first glance it looks like it would be possible to modify that custom serializer to use BSON. But, the Serialize method of the RestSharp.Serializers.ISerializer interface returns a string - which is (I assume) unsuitable for BSON. So, I assume that it would take some more significant changes to RestSharp to implement this change.
Has anyone figured out a way to do this?
Update: I looked at the RestSharp source, and discovered that the RestRequest.AddBody method that takes my object and serializes it into the request body eventually calls Request.AddParameter (with the serialized object data, and the parameter type RequestBody).
I figured that I might be able to serialize my object to BSON and then call Request.AddParameter directly - and indeed I can. However, when RestSharp then executes the RestRequest, it fails to put the binary content into the request, because there are other embedded assumptions about the request content being UTF-8 encoded.
Thus it looks like this hack would not work - there would need to be some changes made to RestSharp itself, and I'm not the man for the job...
Update 2: I decided to have a go at using the debugger to figure out how much of RestSharp I'd have to change to overcome the body-encoding issue, so I swapped out my NuGet version of RestSharp and included the RestSharp project in my solution. And... it worked.
It turns out that there has been a change to RestSharp in the last few months that isn't yet in the NuGet version.
So, you can now use AddParameter and pass in an already-BSON-encoded object, and RestSharp will send it off to the server without complaint.
Per the updates in my question, it turns out that if you have the latest RestSharp source, then instead of this:
request.AddBody(myObject);
... you can do this instead whenever you have a payload that would benefit from using BSON:
using (var memoryStream = new System.IO.MemoryStream())
{
using (var bsonWriter = new Newtonsoft.Json.Bson.BsonWriter(memoryStream))
{
var serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Serialize(bsonWriter, myObject);
var bytes = memoryStream.ToArray();
request.AddParameter("application/bson", bytes, RestSharp.ParameterType.RequestBody);
}
}
Note that the first parameter to AddParameter is supposedly the parameter name, but in the case of ParameterType.RequestBody it's actually used as the content type. (Yuk).
Note that this relies on a change made to RestSharp on April 11 2013 by ewanmellor/ayoung, and this change is not in the current version on NuGet (104.1). Hence this will only work if you include the current RestSharp source in your project.
Gary's answer to his own question was incredibly useful for serializing restful calls. I wanted to answer how to deserialize restful calls using JSON.NET. I am using RestSharp version 104.4 for Silverlight. My server is using Web API 2.1 with BSON support turned on.
To accept a BSON response, create a BSON Deserializer for RestSharp like so
public class BsonDeserializer : IDeserializer
{
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public T Deserialize<T>(IRestResponse response)
{
using (var memoryStream = new MemoryStream(response.RawBytes))
{
using (var bsonReader = new BsonReader(memoryStream))
{
var serializer = new JsonSerializer();
return serializer.Deserialize<T>(bsonReader);
}
}
}
}
Then, ensure your request accepts "application/bson"
var request = new RestRequest(apiUrl, verb);
request.AddHeader("Accept", "application/bson");
And add a handler for that media type
var client = new RestClient(url);
client.AddHandler("application/bson", new BsonDeserializer());
I am having a RESTful service with the following method:
[WebInvoke]
string GetDataFromStringAsString(string xmlString);
My client call to the method is as below:
var client = new RestClient();
client.BaseUrl = serviceBaseUrl;
var request = new RestRequest(method){RequestFormat = DataFormat.Xml};
request.Resource = resourceUrl;
request.AddParameter("text/xml", requestBody,
ParameterType.RequestBody);
var response = client.Execute(request);
Let us take a string to post as "Hello World".
Now the string that i post to the above method gives me a 400 Bad
request. In order to get it working i had to wrap the above string in
a element as shown below:
<string xmlns="http://schemas.microsoft.com/2003/10/
Serialization/">Hello World</string>
Now when i post the above string i get a success response back from
the server.
Why is that i have to manually wrap the string to make it work. Is
there a way that i can achieve to post a string without doing the
above manually.
The only other way that I am aware of is to use stream as your input parameter. e.g.
[WebInvoke]
string GetDataFromStringAsString(stream xmlString);
The problem with .Net 4 WCF REST is that fundamentally WCF only knows how to pass two types of info, either XML or a stream of bytes. Personally, I would use WCF Web API instead of the standard WCF REST library because you are going run into lots more of these kinds of issues.