How to JSON Data Format JavaScript Serializer in ASP.NET - javascript

I am writing an ASP.NET web service. I made the connection to SQL Server. The web service is using a JavaScript serializer. My JSON format:
[{"ID":1,"TCKN":"19","Adi":"zzz","Soyadi":"aa"},
{"ID":2,"TCKN":"99","Adi":"user","Soyadi":"user"}]
But I want this JSON format:
"users": [
{
"ID": "1",
"TCKN": "19",
"Adi": "zzz",
"Soyadi": "aa"
},
{
"ID": "2",
"TCKN": "99",
"Adi": "user",
"Soyadi": "user"
},]
WebServices.cs
[WebMethod]
public string getTumKullanici()
{
JavaScriptSerializer jss = new JavaScriptSerializer();
var json = "";
var tumKullanicilar = from result in mydb.Kullanicilars
select result;
json = jss.Serialize(tumKullanicilar);
return json;
}

My understanding is that the way the JSON is displayed lacks of new line chars etc - that's completely normal and desired, as extra characters are useless for services. To make the JSON more readable to humans, you could use tools that enable formatting, as f.e. addon to Notepad++ or some webapp. But for general use as data in computing I would stick to raw format without the tabulators and new lines.

Whenever you're dealing with JSON data that you need to serialize into C#, go to Json2CSharp
Using that site I've got your C# data model:
public class RootObject
{
public int ID { get; set; }
public string TCKN { get; set; }
public string Adi { get; set; }
public string Soyadi { get; set; }
}
Next you're going to need JSON.NET
You can get that by opening the nuget package manager and searching Newtonsoft.Json
Or use the Package manager console
PM> Install-Package Newtonsoft.Json
Next you're going to need to deserialize that JSON..
string json = #"{""ID"":1,""TCKN"":""19"",""Adi"":""zzz"",""Soyadi"":""aa""},{""ID"":2,""TCKN"":""99"",""Adi"":""user"",""Soyadi"":""user""}]";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
And if you never need to serialize the C# object back into JSON... You can do this.
string backToJson = JsonConvert.SerializeObject(root);
EDIT
You can achieve nesting the under users by wrapping your original object with another class:
public class Users
{
public int ID { get; set; }
public string TCKN { get; set; }
public string Adi { get; set; }
public string Soyadi { get; set; }
}
public class Root
{
public List<User> Users {get;set;}
}
var root = new Root { Users = mydb.Kullanicilars.ToList() };
JsonConvert.SerializeObject(root);

Related

Array inside JSON received empty

I'm sending a JSON object when submitting a form that contains some primitive types and one array of objects from a browser (JavaScript) to an ASP.NET MVC backend, but the array of objects is deserialized as an empty array (list, actually).
I've checked what's being sent using Chrome's inspector and the JSON goes out with the correct values, so I believe the issue is in the backend.
Controller action:
[HttpPost]
public ActionResult FooAction(FooViewModel viewModel)
{
//code
}
FooViewModel:
public class FooViewModel
{
public List<BarViewModel> Bars { get; set; } // <-- What arrives empty, not null
public int PrimitiveProperty { get; set; }
public int OtherPrimitiveProperty { get; set; }
public string LastPrimitiveProperty { get; set; }
}
BarViewModel:
public class BarViewModel
{
public long LongProperty{ get; set; }
public string StringProperty { get; set; }
public bool BoolProperty { get; set; }
}
When debugging the controller's action, Bars is empty (not null).
And this is what Chrome's inspector shows me:
LastPrimitiveProperty: SomeText
PrimitiveProperty: 1
OtherPrimitiveProperty: 9
Bars: [{"LongProperty":274,"StringProperty":"SomeString","BoolProperty":true},{"LongProperty":119,"StringProperty":"SomeString","BoolProperty":false},{"LongProperty":163,"StringProperty":"SomeString","BoolProperty":false}]
[HttpPost]
public ActionResult FooAction([FromBody]FooViewModel viewModel)
{
//code
}
Try this and it should collect the json object

AngularJs Post Object with child collections to a MVC WebAPI

I am working on an AngularJS App, and one of the methods in the service js post data to a web api with a following object structure in C#
public class InvitationModel
{
public string Name { get; set; }
public string Email { get; set; }
public EventModel[] EventList { get; set; }
}
public class EventModel
{
public string EventName { get; set; }
public int TotalAdults { get; set; }
public int TotalChildren { get; set; }
public bool IsAccepted { get; set; }
}
Problem is that when I post this data to a WEBAPI method, my parent level properties serializes correctly except the one that holds the collection. It gets set to null always.
The web API method that recieves the request is :
[AllowAnonymous]
[Route("RSVP")]
[HttpPost]
public bool Submit(InvitationModel invitationModel)
{
return true;
}
So, Name and Email serialize correctly, but EventList is NULL
I did check on the javascript side, and my js object holds both the array and other primitive properties. Issue I guess is at the .NET WebAPI side.
Request payload that gets posted is something like this :
{ "Name":"John Doe",
"EventList":{
"0":{ "TotalAdults":"1",
"TotalChildren":"2",
"EventName":"Event 1 Name"
},
"1":{ "TotalChildren":"2",
"TotalAdults":"2",
"EventName":"Event 2 Name"
},
"2":{ "TotalAdults":"1",
"TotalChildren":"1",
"EventName":"Event 3 Name"
}
}
}
The EventList in your JSON is an object with properties "0", "1", etc.
I guess it should be a JSON array, i.e.
{
"Name":"John Doe",
"EventList": [
{"TotalAdults":"1","TotalChildren":"2","EventName":"Event 1 Name"},
{"TotalChildren":"2","TotalAdults":"2","EventName":"Event 2 Name"},
...
], ...
to be correctly read into your C# eventlist property.

Sending a dictionary of javascript parameters to MVC Controller via JSON

I'm using a third party library and cant really change the way it posts data to my MVC 5 controller.
I cant figure out how to setup my model to receive the data.
The json is a follows...
{
"expiration":"2015-06-14T21:02:52.969Z",
"conditions":[
{"acl":"private"},
{"bucket":"anyoldbucket"},
{"Content-Type":"application/pdf"},
{"success_action_status":"200"},
{"key":"somekey"}
]
}
I tried setting up my model like this...
public class AwsSignatureRequestViewModel
{
public DateTime expiration { get; set; }
public Dictionary<string, string> conditions { get; set; }
}
The expiration date is correctly filled out, and I get the right number of conditions but the keys to the dictionary are numbers (indexes) and the values are null
Any suggestions?
If your model is strict, you will need to make objects for every sub objects.
But if you have a dynamic model, you can read the raw string from your request and parse it with Json.net.
public ActionResult Test(string model)
{
Request.InputStream.Seek(0, SeekOrigin.Begin);
string jsonData = new StreamReader(Request.InputStream).ReadToEnd();
var dynamicObject = JObject.Parse(jsonData);
...
}
dynamicObject will contains all of your json.
IINM, based on the data you're getting, your AwsSignatureRequestViewModel should look something like this:
public class AwsSignatureRequestViewModel
{
public DateTime expiration { get; set; }
public List<Dictionary<string, string>> conditions { get; set; }
}
conditions is an "array of objects".
The way you currently have your model, data would map to something like this (which isn't the case):
{
"expiration": "2015-06-14T21:02:52.969Z",
"conditions":
{
"acl": "private",
"bucket": "anyoldbucket",
....
},
.....
Hth...

ASP.NET Web API - pass a complex type from javascript json

I have an ASP.NET Web API that accepts a POST with a UserModel in it:
[HttpPost]
public object Post(UserModel userModel)
{
// some logic here
}
The UserModel is a complex type that looks like this:
public class UserModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public AddressModel CurrentAddress { get; set; }
}
The AddressModel Model looks like this:
public class AddressModel
{
public string Country { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string Number { get; set; }
}
I'm trying to call this API from javascript and send a JSON object. This is the JSON object I'm sending:
var user = {
Id: 1,
FirstName: 'Hello',
LastName: 'World',
CurrentAddress: {
Country: 'Israel',
City: 'Tel Aviv',
Street: 'Shalom',
Number: '5'
}
};
What I get in my Post method is a UserModel with the UserModel fields filled with the correct information, the CurrentAddrent address is initialized, but the values sent are not there. The values of the parent object (the UserModel object are ok).
What am I doing wrong here? how can you send a complex object to WebAPI Model?
to receive complex data objects in MVC web API actions you have to add [FromBody] attribute to your POST arguments.
The [FromBody] tells the Web API to search for the parameter’s value in the body of a POST request.
[HttpPost]
public void Post([FromBody] UserModel userModel)
{
}
I've made a local test and I obtained the values.
I hope it helps!

deserialize nested json object in c#

I have json object in javascript as
{"CategoryID":"1","CountryID":"1","CountryName":"United Arab Emirates",
"BillerID":"23","AccountNo":"1234567890",
"Authenticators":"{\"ConsumerNumber\":\"1234567890\",\"LastBillDate\":\"14-10-2014\",\"LastBillDueDate\":\"24-11-2014\"}",
"ShortName":"0000000001"}
I have similar c# class as
[Serializable]
public class UserContext
{
public string CategoryID { get; set; }
public string BillerID { get; set; }
public string AccountNo { get; set; }
public string Authenticators { get; set; }
public string ShortName { get; set; }
public string CountryID { get; set; }
public string CountryName { get; set; }
}
I can get each element value in c# as
UserContext obj1 = Deserialize<UserContext>(context);
But as Authenticators is nested json object i want something like this in C#
[Serializable]
public class Authenticators
{
public string ConsumerNumber { get; set; }
public string LastBillDate { get; set; }
public string LastBillDueDate { get; set; }
}
So that i can get each value of each Authenticators element like
string value = obj.ConsumerNumber;
I want to populate two classes with values. How can i achieve the same ?
Your UserContext class has a string field Authenticators, while the json structure suggests it's an object.
Change
public string Authenticators { get; set; }
to
public Authenticators Authenticators { get; set; }
Then you can deserialize the UserContext object along with the nested object Authenticators
UserContext obj1 = Deserialize<UserContext>(context);
var consumerNumber = obj1.Authenticators.ConsumerNumber;
UPDATE:
You probably need to fix javascript code, bacause now it stores already serialized json string as a string field inside UserContext object.
What you have now, is something similar to:
var data =
{
CategoryID:"1",
Authenticators: JSON.stringify({ConsumerNumber:"1234567890"})
};
var json = JSON.stringify(data);
It should be like:
var data =
{
CategoryID:"1",
Authenticators:{ConsumerNumber:"1234567890"}
};
var json = JSON.stringify(data);
just change
public string Authenticators { get; set; }
to
public Authenticators Authenticators { get; set; }
then you can access the properties of the inner object simply by
var number = obj1.Authenticators.ConsumerNumber;
but i noticed that your JSON had some problems when deserializing using Newtonsoft, i had to change the value of Authenticators in the JSON string to
'Authenticators':{'ConsumerNumber':'1234567890','LastBillDate':'14-10-2014','LastBillDueDate':'24-11-2014'},
just remove the backslash
Once you've deserialized the outer object, you can run another deserialize on the Authenticators JSON string, which is now a property on obj1.
This is required because your Authenticators is a string, it is escaped and thus can't be deserialized until the outer object is deserialized.
Authenticators obj2 = Deserialize<Authenticators>(obj1.Authenticators);
string value = obj2.ConsumerNumber;

Categories

Resources