Sending data by JSON - json

I want to send JSON from desktop application to the server with mvc wepApi.
this is my desktop application code ,that convert data to the JSON and send it.
private void btnAddUserType_Click(object sender, EventArgs e)
{
UserType userType = new UserType();
userType.UserTypeName = txtUserTypeName.Text;
string json = JsonConvert.SerializeObject(userType);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3852/api/default1");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
streamWriter.Write(json);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var responseText = streamReader.ReadToEnd();
}
and this is my web api
// POST api/default1
public void Post([FromBody]string value)
{
UserTypeRepository bl = new UserTypeRepository();
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(UserType));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(value));
UserType u = new UserType();
u = (UserType)js.ReadObject(stream);
bl.Add(u);
}
but when post api is calling the Value is null.
why?

using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
streamWriter.Write(json);
You are not flushing nor closing the stream, so basically the data never gets to the api.
My code:
Program.cs - Console App
class Program
{
static void Main(string[] args)
{
var user = new UserModel {Id = 4, FirstName = "Michael", LastName = "Angelo"};
var json = JsonConvert.SerializeObject(user);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:56506/api/Values/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
streamWriter.Write(json);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadKey();
}
}
UserModel.cs - some data class
public class UserModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Id { get; set; }
}
ValuesController.cs - WebApi controller from template
public class ValuesController : ApiController
{
// GET api/values
public UserModel[] Get()
{
return UserProvider.Instance.Get(); // returns some test data
}
// GET api/values/5
public UserModel Get(int id)
{
return new UserModel{Id=1,FirstName="John",LastName="Smith"};
}
// POST api/values
public void Post([FromBody]UserModel value)
{
if (value == null) // BREAKPOINT HERE, just to see what's in value
{
var x = value;
}
}
}
WebApiConfig.cs - default config with added line about Json, but IT WORKS WITHOUT IT -it's so that I can test GET easily in browser etc. ;)
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Result:

Related

Deserialize json shows null in xamarin forms

Hi I have a Login API which I am using to login though my xamarin.forms app.
I will post my username and password and in return I am getting some data.Now Iam facing some issues at deserialization of json. Iam getting data at my resultJson but I cant deserialize it. Help me.
My Json :
[
{
"Result":true,
"ID":"fc938df0",
"LoginName":"test",
"UserName":"test",
"ConnectionString":"MSSQLSERVER;Initial Catalog=Test1;User ID=db;Password=db#2018",
"UserProfileID":"fc938df0"
}
]
My API Call class which have deserialization of Json.
public T APICallResult<T>()
{
try
{
Device.BeginInvokeOnMainThread(() =>
{
if (loadingIndicator != null)
{
loadingIndicator.IsRunning = true;
loadingIndicator.IsVisible = true;
}
});
var client = new HttpClient { BaseAddress = baseAddress };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var req = new HttpRequestMessage(HttpMethod.Post, apiurl);
req.Content = new StringContent(postdata, Encoding.UTF8, "application/json");
string stringObtained = "";
Task<string> task = Task.Run(async () => await Threading(client, req));
task.Wait();
stringObtained = task.Result;
var jsonObtained = Regex.Unescape(stringObtained);
int startIndex = jsonObtained.IndexOf('[');
int endIndex = jsonObtained.LastIndexOf(']');
int length = endIndex - startIndex + 1;
var resultJSON = jsonObtained.Substring(startIndex, length);
T resultObject;//Generic type object
try
{
//**Deserializing**
resultObject = JsonConvert.DeserializeObject<T>(resultJSON);//, settings);
removeLoadingAnimation();
return resultObject;
}
catch (Exception e)
{
List<ErrorMessageData> errorMessages = JsonConvert.DeserializeObject<List<ErrorMessageData>>(resultJSON);
errorMessage = errorMessages[0];
removeLoadingAnimation();
return default(T);
}
}
catch (Exception e)
{
errorMessage = new ErrorMessageData();
errorMessage.Flag = false;
errorMessage.Message = e.Message;
removeLoadingAnimation();
return default(T);
}
}
My API call at login class
string postdataForLogin = "{\"userName\":\"" + userName.Text + "\",\"password\":\"" + password.Text + "\",\"RequestURL\":\"" + CommonValues.RequestURL + "\"}";
APICall callForLogin = new APICall("/API/LoginMobile/HomeLogin", postdataForLogin, loadingIndicator);
try
{
List<LoginData> resultObjForLogin = callForLogin.APICallResult <List<LoginData>>();
if (resultObjForLogin != null)
{
LoginData loginData = new LoginData();
loginData = resultObjForLogin[0];
Settings.userID = loginData.UserProfileID;
Settings.connectionString = loginData.ConnectionString;
if (loginData.Result)
{
Device.BeginInvokeOnMainThread(async () =>
{
Navigation.InsertPageBefore(new MainPage(), this);
await Navigation.PopAsync();
});
}
My DataModel
public class LoginData
{
public bool Result { get; set; }
public string ID { get; set; }
public string UserProfileID { get; set; }
public string LoginName { get; set; }
public string UserName { get; set; }
public string ConnectionString { get; set; }
}
Its seems strange, My problem solved after downgrading my xamarin.forms from latest version to pre release 4.0.0.169046- pre5. I think its a xamarin forms bug

JSON Property not binding to JSON.NET PropertyName in ASP.NET MVC 5 Post request

I am banging my head hear on why my property ReCaptchaResponse JSONProperty will not bind to my model. The others do just find, and my JSON Value Provider class hits just fine. Any clue at all? It is always NULL.
Ajax Request
{"Name":"Joe","Email":"","Message":"","g-recaptcha-response":"data"}
ContactUsController.cs
[HttpPost]
public virtual ActionResult Index(ContactUsModel model)
{
_contactUsService.ContactUs(model);
return Json(new SuccessResponse("Submitted Successfully"));
}
ContactUsMode.cs
[JsonObject, DataContract]
public class ContactUsModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Message { get; set; }
[JsonProperty(PropertyName = "g-recaptcha-response"), DataMember(Name = "g-recaptcha-response")]
public string ReCaptchaResponse { get; set; }
}
JsonNetValueProviderFactory.cs
namespace Tournaments.Models.Mvc
{
public class JsonNetValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
// first make sure we have a valid context
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
// now make sure we are dealing with a json request
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return null;
// get a generic stream reader (get reader for the http stream)
var streamReader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
// convert stream reader to a JSON Text Reader
var jsonReader = new JsonTextReader(streamReader);
// tell JSON to read
if (!jsonReader.Read())
return null;
// make a new Json serializer
var jsonSerializer = new JsonSerializer();
jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
// add the dyamic object converter to our serializer
jsonSerializer.Converters.Add(new ExpandoObjectConverter());
// use JSON.NET to deserialize object to a dynamic (expando) object
Object jsonObject;
// if we start with a "[", treat this as an array
if (jsonReader.TokenType == JsonToken.StartArray)
jsonObject = jsonSerializer.Deserialize<List<ExpandoObject>>(jsonReader);
else
jsonObject = jsonSerializer.Deserialize<ExpandoObject>(jsonReader);
// create a backing store to hold all properties for this deserialization
var backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
// add all properties to this backing store
AddToBackingStore(backingStore, String.Empty, jsonObject);
// return the object in a dictionary value provider so the MVC understands it
return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
}
private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
{
var d = value as IDictionary<string, object>;
if (d != null)
{
foreach (KeyValuePair<string, object> entry in d)
{
AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
}
return;
}
var l = value as IList;
if (l != null)
{
for (int i = 0; i < l.Count; i++)
{
AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
}
return;
}
// primitive
backingStore[prefix] = value;
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
}
}
}
Try ModelBinder. ValueProviderFactory does not work because of ExpandoObject.
internal class JsonNetModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
controllerContext.HttpContext.Request.InputStream.Position = 0;
var stream = controllerContext.RequestContext.HttpContext.Request.InputStream;
var readStream = new StreamReader(stream, Encoding.UTF8);
var json = readStream.ReadToEnd();
return JsonConvert.DeserializeObject(json, bindingContext.ModelType);
}
}
ContactUsController.cs
[HttpPost]
public virtual ActionResult Index([ModelBinder(typeof(JsonNetModelBinder))]ContactUsModel model)
{
_contactUsService.ContactUs(model);
return Json(new SuccessResponse("Submitted Successfully"));
}

how to Deserialize Json response from WCF Restful Service?

I want to deserialize a Json response into my class object. I have created a WCF Restful Service, and from client using proxy object I'm calling a service method which return me a json. Now I want to convert that json into my class object.
My service is as follow:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "GetProject/{projectID}")]
tblProject GetProject(String projectID);
Implementations:
public tblProject GetProject(String projectID)
{
tblProject pro = new tblProject();
pro = DAL.ProjectDAL.GetProject(Convert.ToInt32(projectID));
return pro;
}
and from controller in MVC I'm making request as:
public ActionResult Index()
{
var request = (HttpWebRequest)WebRequest.Create("http://localhost:8733/Design_Time_Addresses/RestServiceLibrary.RESTService/REST_ProjectService/getproject/2");
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string txtResult = reader.ReadToEnd();
return view();
}
and when I run I'm getting response as:
and when I call through a proxy method I got exception:
but my endpoints are there in config as,
you can use javascriptserializer
string s = "YouJsonText";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize(s);
//or
YouCustomClass res = serializer.Deserialize<YouCustomClass>(sb.ToString());
Also, you can use CustomJsonConverter like this:
public class YouCustomClassConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
//and first you need register type, which you want Deserialize
public override IEnumerable<Type> SupportedTypes
{
get { return new[] { typeof(YouCustomClass ) }; }
}
}
//and then example of using JavaScriptSerializer with custom converter
var ser = new JavaScriptSerializer();
ser.RegisterConverters(new JavaScriptConverter[] { new YouCustomClassConverter() });
try
{
YouCustomClass obj = ser.Deserialize(jsonString);
}
Note: you need use using System.Web.Script.Serialization;
class GetProjectResultWrapper
{
public GetProjectResult GetProjectResult{ get; set; }
}
class GetProjectResult
{
public string id {get;set;}
.....
......
}
JavaScriptSerializer ser = new JavaScriptSerializer();
GetProjectResultWrapper response = ser.Deserialize<GetProjectResultWrapper>(sb.ToString());
response .GetProjectResult;

Fetching json array, null pointer refrence exception

{"names":["name1","name2","name3","name4"]}
I need to fetch this and show them in a list. What I am doing is
public class brand
{ public string Name
{ get; set; }
}
public class brands
{ public list<brand> Names
{ get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
getdata();
}
private void getdata()
{
string uri = "URL";
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(new Uri(uri));
req.BeginGetResponse(new AsyncCallback(show), req);
}
private void show(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
StreamReader stream1 = new StreamReader(response.GetResponseStream());
string s1 = stream1.ReadToEnd();
var ser = new DataContractJsonSerializer(typeof(brands));
var stream = new MemoryStream(Encoding.Unicode.GetBytes(s1));
var bb = (brands)ser.ReadObject(stream);
foreach (var ev in bb.Names)
{
textBlock1.Text = ev.Name.ToString();
}
}
This I made after reading blog posts. I am getting NullReferenceException.
Please tell me where I am doing wrong or alternative way to do the same.
First learn how to parse your JSON data. Consider this as a json string.
String jsonData = #"{""names"":[""name1"",""name2"",""name3"",""name4""]}";
var brands = JsonConvert.DeserializeObject<Brands>(jsonData);
foreach (var item in brands.names)
{
Console.WriteLine(item);
}
Where your Brands class is like this
public class Brands
{
public List<string> names { get; set; }
}
This above code explains how to parse your json data. Now, coming to fetching your json data from web service, as your request is not a POST request (it appears to be get from your code), you can use a simple WebCleint.
void getData()
{
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri("url"));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var brands = JsonConvert.DeserializeObject<Brands>(e.Result);
foreach (var item in brands.names)
{
Console.WriteLine(item);
}
}
Check this blog for any other doubts : Parsing JSON in a Windows Phone Application

WebInvoke Parameter is NULL

I have a service where the operation contract looks like the following. I have a WebInvoke attribute and the method is set to POST. I do have a UriTemplate. The actual service method name is SaveUser. I am trying to pass in a User object (a data contract with properties annotated as data member attributes).
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "SaveUser", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json)]
User SaveUser(User user);
The client looks like the following. For simplicity I have excluded the token and authorization etc.:
using (WebClient webClient = new WebClient())
{
try
{
Random r = new Random();
var partitionKey = Guid.NewGuid().ToString();
var rowKey = r.Next(999900, 999999).ToString();
User u = new User()
{
UserId = partitionKey,
FirstName = "First-" + DateTime.Now.Ticks.ToString(),
LastName = "Last-" + DateTime.Now.Ticks.ToString(),
LoginName = rowKey,
Password = "password1",
PayPalEmailAddress = "First" + DateTime.Now.Ticks.ToString() + "#verascend.com",
PhoneNumber = "+1206" + r.Next(1234567, 9999999).ToString()
};
string url = serviceBaseUrl + "/SaveUser";
webClient.Headers["Content-type"] = "application/json; charset=utf-8";
// webClient.Headers[HttpRequestHeader.Authorization] = authToken;
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
using (var memStream = new MemoryStream())
{
ser.WriteObject(memStream, u);
Debug.WriteLine("-------------> "+ByteArrayToString(memStream.ToArray()));
webClient.UploadData(url, "POST", memStream.ToArray());
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
string responseText = string.Empty;
using (Stream responseStream = ((HttpWebResponse)ex.Response).GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(responseStream))
{
responseText = streamReader.ReadToEnd();
}
}
throw new Exception(responseText);
}
else
{
throw new Exception(ex.Message.ToString());
}
}
}
Problem: The service method (actual service) is receiving the param (User) as NULL. What am I doing wrong? I tried adding the known type in the service contract but no luck.
Your problem is that you define your operation to have a wrapped request. That means that the parameter, instead of being sent as a "plain" JSON object, must be wrapped in a JSON object, and the member name must correspond to the parameter name (in your case, user). The code below does the wrapping; you can see that with that the parameter now is properly received by the server. Another option would be to change the BodyStyle property to Bare instead of WrappedRequest as you have (in which case you'd need to send the plain object to the service operation).
public class StackOverflow_12452466
{
[ServiceContract]
public interface ITest
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "SaveUser", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json)]
User SaveUser(User user);
}
public class Service : ITest
{
public User SaveUser(User user)
{
Console.WriteLine("User: {0}", user);
return user;
}
}
public class User
{
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string LoginName { get; set; }
public string Password { get; set; }
public string PayPalEmailAddress { get; set; }
public string PhoneNumber { get; set; }
public override string ToString()
{
return string.Format("Id={0},First={1},Last={2},Login={3},Pwd={4},PayPal={5},Phone={6}",
UserId, FirstName, LastName, LoginName, Password, PayPalEmailAddress, PhoneNumber);
}
}
public static void Test()
{
string serviceBaseUrl = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(serviceBaseUrl));
host.AddServiceEndpoint(typeof(ITest), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
host.Open();
Random r = new Random();
User u = new User()
{
UserId = "partitionKey",
FirstName = "First-" + DateTime.Now.Ticks.ToString(),
LastName = "Last-" + DateTime.Now.Ticks.ToString(),
LoginName = "rowKey",
Password = "password1",
PayPalEmailAddress = "First" + DateTime.Now.Ticks.ToString() + "#verascend.com",
PhoneNumber = "+1206" + r.Next(1234567, 9999999).ToString()
};
string url = serviceBaseUrl + "/SaveUser";
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json; charset=utf-8";
Func<byte[], string> ByteArrayToString = (b) => Encoding.UTF8.GetString(b);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
try
{
using (var memStream = new MemoryStream())
{
byte[] wrappingStart = Encoding.UTF8.GetBytes("{\"user\":");
memStream.Write(wrappingStart, 0, wrappingStart.Length);
ser.WriteObject(memStream, u);
byte[] wrappingEnd = Encoding.UTF8.GetBytes("}");
memStream.Write(wrappingEnd, 0, wrappingEnd.Length);
Debug.WriteLine("-------------> " + ByteArrayToString(memStream.ToArray()));
webClient.UploadData(url, "POST", memStream.ToArray());
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
string responseText = string.Empty;
using (Stream responseStream = ((HttpWebResponse)ex.Response).GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(responseStream))
{
responseText = streamReader.ReadToEnd();
}
}
throw new Exception(responseText);
}
else
{
throw new Exception(ex.Message.ToString());
}
}
}
}