Deserialize keyvalue string to object - c#

Hi can anybody help me out from this.
I have an HTML page. This page contains Textboxes for FirstName,MiddleName, LastName, etc.
On button clcik of this HTML page i am calling a javascript function. Here i am getting all the HTML page contaols and its value using JQuery Serialization. Then passing this values to my WCF service hosted in server.
This service will parse this string into corresponding objects and save the values into the database.
So In HTMl page i written the Javascript function like below:
pmamml.ButtonClick = function() {
var formData = $("#form1").serializeArray();
var stringJson;
$.getJSON('ajax/test.json', function(formData) {
stringJson= JSON.stringify(formData)
});
//alert(stringJson);
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/Update?formData=' + JSON.stringify(formData),
error: pmamml.ajaxError,
success: function(msg) {
document.write(msg);
//alert(msg);
},
});},
And in WCF service i written:
[WebInvoke(Method = "GET", UriTemplate = "/Update?formData={formData}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public string Update(string formData)
{
// Here i am receiving formdata string as
// formData = "[{\"name\":\"FirstName\",\"value\":\"Pankaj\"},{\"name\":\"MiddleName\",\"value\":\" \"},{\"name\":\"LastName\",\"value\":\"KUMAR\"}]";
}
I wanna deserialize this string into List object or keyvaluepair or Dictionary any one of the above format.
So that i can save this value into database.
How can we do this. Thanks in advance.

The easiest way to do it would be to split it into an array using RegEx, matching \"([^\"]*).
update Given you are sending it to a web service, it should just be configured as Json to deserialize it automatically

The code below will give you your stringdata seperated into workeable pieces, as displayed below.
// new list
var l = new List<string>();
// original data
var s = "[{\"name\":\"FirstName\",\"value\":\"Raja\"},{\"name\":\"MiddleName\",\"value\":\"Raja \"},{\"name\":\"LastName\",\"value\":\"KUMAR\"}]";
// clean up and split in larger parts
var d = s.Substring(1, s.Length - 2).Replace("\\", "").Replace("\"", "").Replace("}", "").Split('{');
// Split in final entries and add to list
var sb = new char[2] { ',', ':' };
foreach (var r in d) { l.AddRange(r.Split(sb, StringSplitOptions.RemoveEmptyEntries));
// Contents of the List will be
name
FirstName
value
Raja
name
MiddleName
value
Raja
name
LastName
value
KUMAR
// The code is not very robust yet, e.g. you need to check your inputstring is not empty

yup i got the solution
This is my updated JQuery
pmamml.ButtonClick = function() {
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var stringJson = JSON.stringify($('#form1').serializeObject());
var Userdata = "formData=" + stringJson;
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/Update?' + Userdata,
error: pmamml.ajaxError,
success: function(response, status, xhr) {
if (response = true) {
//alert(response);
alert("Data Updated Successfully");
}
}
});
}
In above method formData will pass the JSON string like below:
{ "FirstName":"Raja","MiddleName":"Raja","LastName":"Kumar"}.
And in my WCF Service, converted this JSON string to Object.
[WebInvoke(Method = "GET", UriTemplate = "/Update?formData={formData}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public bool Update(string formData)
{
var mlParser = new MLParser();
System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
var InfoList = s.Deserialize<Users>(formData);
return mlParser.Update(InfoList);
}
public class Users
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
This is working fine.
Thnak you all for your kind response.. :)

Related

WCF Service's JSON string response to Ajax POST request is not accepted. Method always goes to error.

I have written a WCF service which in theory, should accept a JSON object from Ajax and return true or false as a response to indicate the JSON object was accepted from service and sent to the database.
This is how the interface is implemented in IService
[OperationContract]
[WebInvoke(Method ="POST",ResponseFormat=WebMessageFormat.Json,RequestFormat =WebMessageFormat.Json,UriTemplate ="InsertPatient")]
String InsertPatient(Patient PatientObj);
The contract is implemented as follows
public String InsertPatient(Patient PatientObj)
{
PatientContext pat = new PatientContext();
Boolean boolObj = new Boolean();
string JsonString = "";
if (pat.Patients.Where(x => x.Username == PatientObj.Username).Any())
{
// Username already taken;
boolObj = false;
JsonString =JsonConvert.ToString(boolObj);
return JsonString;
}
else
{ //Initiate to add user to login table
Login log = new Login();
log.Username = PatientObj.Username;
log.Password = PatientObj.Password;
log.User_Type = PatientObj.User_Type;
if (InsertLogin(log)) //if login added
{
pat.Patients.Add(PatientObj); //add user to patient table
pat.SaveChanges();
boolObj = true;
JsonString = JsonConvert.ToString(boolObj);
return JsonString;
}
else //login was not added
{
boolObj = false;
JsonString = JsonConvert.ToString(boolObj);
return JsonString;
}
}
}
and finally the Ajax script is implemented as follows
<script>
$(document).ready(function () {
$("form").submit(function () {
var L_Username = $("#UN").val();
var L_User_Type = "patient";
var L_Name = $("#name").val();
var L_Birthday = $("#bday").val();
var L_Gender = $("input[name='optradio']:checked").val();
var L_Contact = $("#cNo").val();
var L_Password = $("#password").val();
var L_Address = $("#adress").val();
var jsondata = {
Username: L_Username,
User_Type: L_User_Type,
Address: L_Address,
Birthday: L_Birthday,
Contact: L_Contact,
Gender: L_Gender,
Name: L_Name,
Password: L_Password
};
console.log(JSON.stringify(jsondata));
$.ajax({
url: "http://localhost:50709/Service1.svc/rest/InsertPatient",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(jsondata),
success: function (resultdata) {
alert("inserted");
},
error: function (e) {
alert("Something went wrong");
}
});
});
});
</script>
When I test this through POST-man , I get the correct response as true or false. But when I run this from the website itself. Ajax always throw the error alert, but the values get successfully added to the tables.
What am I doing wrong , please help. Thank you in advance.

Send File with extra parameters to WCF REST Service

I am having a little problem here.
Currently I am using a Generic Handler to upload files to the server, but one problem that I have is that if I have extra data, like a user's name and surname, I have to do(save) that separately.
This is a problem, because if I save the name and surname, and the file upload fails, I have a record in my database that has no file associated with it.
So, now I am thinking of implementing a new web method, that will take all of this, and if that method fails, it will just roll back the SQL transaction.
What I want to do is call a web method, and pass the file with the user's name and surname and photo, and then perform the saving in the database there.
This is what I have tried:
jQuery:
$("#btnCreateRequest").click(function () {
var data = new FormData();
var photo = $("#fuPhoto")[0].files[0];
data.append("name", 'Fred');
data.append("surname", 'Moller');
data.append("photo", photo);
$.ajax({
type: "POST",
url: "Service.svc/CreateRequest",
dataType: "json",
//cache: false,
contentType: false,
processData: false,
data: data,
success: function (response2) {
//$("#PageArea").html(response2);
Popup(true, "success", "success", true);
},
error: function (response) {
Popup(true, "Error", JSON.stringify(response), true);
}
});
});
IService.cs
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "CreateRequest",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string CreateRequest();
Service.svc
public string CreateRequest()
{
var request = System.Web.HttpContext.Current.Request;
string name = request["name"];
string surname = request["surname"];
HttpPostedFile photo = request["photo"];
//Saving in database happens here, using above variables...
return "whatever";
}
However, I am failing miserably.
The web service gets called, but all the variables is NULL.
If I am going about this the wrong way, please point me in the right direction - any help will be appreciated!
(If something is not clear, please ask and I'll try to explain more)
Ah, no matter, I've changed my approach. Instead of trying to use a Web Service, I now use the Generic Handler for this.
Sometimes, it's better to look at it a little different.
Here is how I got this to work for me.
In my jQuery, I will have something like this:
$("#btnCreateRequest").click(function () {
var data = new FormData();
var photo = $("#fuPhoto")[0].files[0];
data.append("callingFromPage", "help");
data.append("requestType", $('#dropBugType').val());
data.append("description", $('#taDescription').val());
data.append("photo", photo);
data.append("userGUID", _cookieObject.UserObject.GlobalUniqueID);
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
//Indicate progress.
$('.uplPhotoProgress').css('width', percentComplete + '%');
$('.uplPhotoProgress').html('Uploading: ' + percentComplete + '%');
//Hide progress bar.
if (percentComplete === 100) {
$//('.uplProgressAttachments').css('display', percentComplete + 'none');
}
}
}, false);
return xhr;
},
url: "UploadHandler.ashx/",
data: data,
processData: false,
contentType: false,
type: "POST",
success: function (response) {
if (response === 'success') {
console.log('success');
} else {
console.log('problem...');
}
},
error: function (response) {
}
});
});
Then, in my UploadHandler.ashx (Generic Handler):
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "multipart/form-data";
context.Response.Expires = -1;
try
{
string callingFromPage = context.Request["callingFromPage"];
if (!string.IsNullOrWhiteSpace(callingFromPage))
{
switch (callingFromPage)
{
case "help":
{
string requestType = context.Request["requestType"];
string description = context.Request["description"];
HttpPostedFile photo = context.Request.Files[0];
string guid = context.Request["userGUID"];
//DO YOUR STUFF >>>
context.Response.Write("success");
break;
}
}
}
catch (Exception ex)
{
context.Response.Write("Error: " + ex.Message);
}
}
Sure, this is a simple example of what I did... but I'm happy to do it this way.

How to deserialize Json Stream in c#

I have following method and i need to deserialize the retrieve stream.
public void RedirectHyperlink(System.IO.Stream jsonString)
{
string val= JsonSteamToString(jsonString);
}
public string JsonSteamToString(Stream jsonStream)
{
StreamReader reader = new StreamReader(jsonStream);
return reader.ReadToEnd();
}
My class is as follows:
public class H2JsonStateObject
{
public string url { get; set; }
public string stateId { get; set; }
}
I'm calling this method using Ajax call as follows:
var value ="89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9";
var link="RedirectPage.aspx";
var data = '{"url":"' + link + '","stateId":"' + value + '"}';
var jsonToSend = JSON.stringify(data);
$.ajax({
cache: false,
url: "StateRedirectService.svc/RefreshPagemethod",
type: "POST",
async: false,
data: jsonToSend,
success: function (data, textStatus, jqXHR) {
window.location.href = link;
},
error: function (xhr, status, error) {
alert('error');
}
});
When the request receive to web method and after converting the value it get following string.
"\"{\\\"url\\\":\\\"RedirectPage.aspx\\\",\\\"stateId\\\":\\\"89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9\\\"}\""
Now i need to deserialize url & stateId. How can i do that?
I tried followings. but couldn't able to deserialize.
Using DataContractJsonSerializer
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(val)))
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(H2JsonStateObject));
H2JsonStateObject p2 = (H2JsonStateObject)deserializer.ReadObject(ms);
}
It throws exception and says :
Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''.
Using JavaScriptSerializer
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Object obj = serializer.DeserializeObject(val);
This gives me my object as string value as follows:
"{\"url\":\"RedirectPage.aspx\",\"stateId\":\"89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9\"}"
What I did wrong and how can i get RedirectPage.aspx and 89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9 value?
Able to solve this problem in following way. my problem is with Json string value.
public void RedirectHyperlink(System.IO.Stream jsonString)
{
string val = JsonSteamToString(jsonString);
string JsonVal = val.Replace("\"", "'");
var json_serializer = new JavaScriptSerializer();
H2JsonStateObject myobj = json_serializer.Deserialize<H2JsonStateObject>(JsonVal);
H2RequestRedirect.RedirectToTemp(myobj.url, myobj.stateId);
}
in here string needs to be in following format.
JsonVal = "{'url': 'RedirectPage.aspx','stateId': '89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9' }";
When i'm calling this method i send json object without JSON.stringify(data);
var data = '{"url":"' + link + '","stateId":"' + value + '"}';
$.ajax({
cache: false,
url: "StateRedirectService.svc/RedirectHyperlink",
type: "POST",
async: false,
data: data,
success: function (data, textStatus, jqXHR) {
//alert('OK');
window.location.href = link; },
error: function (xhr, status, error) {
alert('error');
}
});
Then it works as a charm...

Javascript and C# Handler - AJAX with JSON, sending array

When I send an array with AJAX (using JSON), my C# handler does not know how to handle the whole query (suddenly the querystrings combine with each other for some reason).
In this example I'm sending a very simple array to the server and the server says the querystring Name is null (but it is not null); Sending any request without the array works fine.
On that note, would appreciate if anyone could explain what the array looks like on the URL (if I wanted to send a request through the browser for example).
AJAX code:
function btnClick() {
var arr = new Array();
arr[0] = "Hey";
arr[1] = "Stackoverflow";
arr[2] = "What's your name?";
var jsonParam = { Name: "test", Pass: "123", Stuff: arr }
$.ajax({
url: "Test.ashx",
type: "get",
data: JSON.stringify(jsonParam),
dataType: "json",
contentType: 'application/json; charset=utf-8',
async:false,
success: function (response) {
alert(response.Name);
}
});
}
Handler code:
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
JavaScriptSerializer jss = new JavaScriptSerializer();
string res = jss.Serialize(new UserInfo { Name = context.Request.QueryString["Name"], Pass = "pass" + context.Request.QueryString["Pass"], Stuff = new string[] { "1", "2" } });
context.Response.Write(res);
}
You cannot get the json from querystring.
You can use this; You should install NewtonJsonfor JSonConvert from nuget. If you don't want that, you can use JavaScriptSerializer instead of that.
protected object FromJsonToObject(Type t)
{
Context.Request.InputStream.Position = 0;
string json;
using (var reader = new StreamReader(Context.Request.InputStream))
{
json = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject(json, t);
}

iterate through JSOn result

I have a WebMethod being called from ajax, trying to iterate through the returned data. The data being returned is "{ BusinessTypeID = 2 }". I'm trying to figure out how to just get the value 2?
//Function called from ajax
[System.Web.Services.WebMethod]
public static string[] GetTerminalBusinessTypes(string terminalID)
{
DataClassesDataContext db = new DataClassesDataContext();
List<string> results = new List<string>();
try
{
var terminalBusinessTypes = (from bt in db.BusinessTypes
join obt in db.OxygenateBlenderBusinessTypes on bt.BusinessTypeID equals obt.BusinessTypeID
where obt.OxygenateBlenderID == Convert.ToInt32(terminalID)
select new
{
bt.BusinessTypeID
}).ToList();
for (int i = 0; i < terminalBusinessTypes.Count(); i++)
{
results.Add(terminalBusinessTypes[i].ToString());
}
}
catch (Exception ex)
{
}
return results.ToArray();
}
The ajax function:
function PopulateTerminalBusinessTypes(terminalID) {
$.ajax({
type: "POST",
url: "OxygenateBlenderCertificationApplication.aspx/GetTerminalBusinessTypes",
data: "{'terminalID':" + terminalID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var targetValue = data.d;
var items = $('#cblTerminalBusinessType input:checkbox');
$.each(targetValue, function (key, targetValue) {
alert(data[index].BusinessTypeID);
});
}
})//end ajax
}
When your web service returns the json value, asp.net wraps in an object, with the key being d and the value being your json string. Review this link for more info.
You have to parse the value string into a json object. Using jQuery (v1.4.1 or higher):
jQuery.parseJSON(targetValue);
To be honest I cannot see where your "index" is defined.
Shouldn't the alert line read
$each(targetVale, function(key, item) {
// on second look, this wont work as you are converting toString()
alert(targetValue[key].BusinessTypeId)
// this should
alert(item)
});
You could also throw a debugger; line above the alert and see the values being traversed.
You may want to try returning a JSON string from C#:
public static **string** GetTerminalBusinessTypes(string terminalID)
...
var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(results);
return sJSON;

Categories

Resources