Always returning XML string with Json in WCF service
I have a WCF service that always returns:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"> JSON STRING </string>
I just want JSON STRING. I read some posts here on stackoverflow and tried solutions, but I couldn't get anywhere. Here is my code:
[ServiceContract]
public interface IUserService
{
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetUserById?x={uid}")]
string getUserByUID(string uid);
Interface execution:
public class UserService : IUserService
{
public string getUserByUID(string uid)
{
UserDAO mUserDAO = UserService.getUserDAO();
User mUser = mUserDAO.getUserByUID(Convert.ToInt64(uid));
if (mUser != null)
{
mUserDAO.close();
return JsonConvert.SerializeObject(mUser);
}
Web configuration:
<behavior name="restfulBehavior">
<webHttp />
</behavior>
The call made by Retrofit:
D/Retrofit﹕ ---> HTTP GET http:http://localhost/UserService.svc/GetUserById?x=1
D/Retrofit﹕ Content-Type: application/json
D/Retrofit﹕ ---> END HTTP (no body)
Return from server
D/Retrofit﹕ <--- HTTP 200 http://localhost/UserService.svc/GetUserById?x=1 (92ms)
D/Retrofit﹕ Content-Length: 446
D/Retrofit﹕ Content-Type: application/xml; charset=utf-8
D/Retrofit﹕ Server: Microsoft-IIS/7.5
D/Retrofit﹕ X-Powered-By: ASP.NET
D/Retrofit﹕ Date: Thu, 18 Jun 2015 03:32:53 GMT
D/Retrofit﹕ OkHttp-Selected-Protocol: http/1.1
D/Retrofit﹕ OkHttp-Sent-Millis: 1434598232505
D/Retrofit﹕ OkHttp-Received-Millis: 1434598232588
D/Retrofit﹕ <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">{JSON STRING}</string>
D/Retrofit﹕ <--- END HTTP (446-byte body)
What am I missing here?
Thanks in advance.
source to share
To receive the JSON response, you need to declare a content type and an accept type.
I'm not sure what you call your service. I'll write an example in C #. However, it can be easily translated into any other language.
WebClient wc = new WebClient();
wc.Headers.Add("Content-Type", "application/json; charset=utf-8");
wc.Headers.Add("Accept", "application/json");
wc.DownloadString("http://yourUrl.com/GetUserById?x=1");
This works for me :)
source to share
Regarding the problem, it was an infrastructure problem. FTP did not update the site, and updates in the code were not reflected in testing.
But I found that my code was wrong too. Below you can find the one that works now. I hope this can help anyone.
public class UserService : IUserService
{
public User getUserByUID(string uid)
{
UserDAO mUserDAO = UserService.getUserDAO();
User mUser = mUserDAO.getUserByUID(Convert.ToInt64(uid));
if (mUser != null)
{
mUserDAO.close();
return mUser;
}
source to share