whats the equivalent for creating json serialized data for this javascript code:
chartData.push({date: "bla",value1: "bla1",value2: "bla2"});
chartData.push({date: "blx",value2: "blax2"});
The json will look something like this:
[{
"date": bla,
"value1": bla1,
"value2": bla3,
}, {
"date": blx,
"value2": blax2
}]
I tried creating a list of class, but when i dont assign the value1 property, the value will just be zero. But i dont want the property to be displayed in the json at all, when not assigned.
List <Models.HistoClass> HistoData= new List<Models.HistoClass>();
HistoData.Add(new Models.HistoClass {date="bla",value1="bla1",value2="bla3"});
HistoData.Add(new Models.HistoClass { date= "blx", value2="blax2" });
How should i create the datamodel to have a json like that?
Thanks!
If you're creating data manually in the way you show, you could use anonymous types to construct data the looks exactly how you want:
List <object> HistoData= new List<object>();
HistoData.Add(new {date="bla",value1="bla1",value2="bla3"});
HistoData.Add(new { date= "blx", value2="blax2" });
However, if you want to use a strong type and/or your code is initializing the values in the same way every time, but sometimes values just aren't present, then you can make the values nullable and tell JSON.NET to ignore null properties when serializing:
public class HistoClass
{
public string date;
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
public int? value1;
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
public int? value2;
}
...
List <Models.HistoClass> HistoData= new List<Models.HistoClass>();
HistoData.Add(new Models.HistoClass {date="bla",value1="bla1",value2="bla3"});
HistoData.Add(new Models.HistoClass { date= "blx", value2="blax2" });
You can use Json.NET's ShouldSerialize:
Public class DateAndValues
{
public DateTime Date {get; set;}
public Int32 Index {get; set;}
public Int32 Value1 {get; set;}
public Int16 Value2 {get; set;}
public bool ShouldSerializeValue1 ()
{
// your condition for serialization, for example even objects:
this.Index % 2 != 0;
}
}
This description:
To conditionally serialize a property, add a method that returns boolean with the same name as the property and then prefix the method name with ShouldSerialize. The result of the method determines whether the property is serialized. If the method returns true then the property will be serialized, if it returns false then the property will be skipped.
is taken from this link.
To actually serialize, of course, use:
var firstObj = new DateAndValues { Index = 1, .. };
var secondObj = new DateAndValues { Index = 2, .. };
string json =
JsonConvert.SerializeObject(new[] {firstObj, secondObj}, Formatting.Indented);
and according to the condition above, secondObj (even Index) will not have Value1.
Related
I'm new to spring boot development. I have to put my json object inside my model object and send it to view. I've used jackson library's ObjectMapper class to convert the object into String.
My controller snippet is
#GetMapping("/show-employee")
public String showEmployee(Model model) {
ObjectMapper objectMapper = new ObjectMapper();
String empString = objectMapper.writeValueAsString(new Employee("santhosh", "kumar", "example#gmail.com"))
model.addAttribute("employee", empString);
return "employees/employee-display";
}
And my model class is
#Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotBlank
#Size(min = 3, max = 20)
private String firstName;
#NotBlank
#Size(min = 3, max = 20)
private String lastName;
#Email(message = "Please enter a valid email id")
private String email;
// constructors, getters and setters
On the view side, I have thymeleaf code as below to access the JSON object
<script>
var employeesJsonStr = "[[${employee}]]";
console.log(employeesJsonStr);
</script>
But on the console window, I end up with this...
{"id":0,"firstName":"santhosh","lastName":"kumar","email":"example#gmail.com","projects":null}
How can pass the JSON String to front end so that I can access that using Javascript without having to do html decoding.
I understand you are converting JSON object as string and setting it up inside a model. This is obviously produce String in the front end instead what you could directly send the model object in the response. It will produce JSON data at the end anyway.
#GetMapping("/show-employee" , produces = MediaType.APPLICATION_JSON_VALUE)
public List<Employee> showEmployee(Model model) {
Employee emp = new Employee("santhosh", "kumar", "example#gmail.com"))
model.addAttribute("employee", emp);
return "employees/employee-display";
}
I'm using asp.net MVC4 for web app development.
I would like to traverse a list of objects from a ViewModel.
Below is the class of the object:
public class User
{
public int Id {get; set;}
public string Name {get; set;}
public string Address {get; set;}
public string Department {get; set;}
}
Below is my ViewModel class:
public class UserViewModel
{
public List<User> AllUsers {get; set;}
public bool IsDeleted {get; set;}
}
As seen in the UserViewModel class, I have a list of objects of type User. Now i would like to iterate through each of the user object in AllUsers list using Jquery and fetch data from them.
In order to do so, I tried doing something like the following:
$(#Model.AllUsers).each( function(){ .... });
I have tried different combination using the above approach, but couldn't succeed. Can anyone suggest a solution for the same.
Thanks in advance.
Assign your collection to a javascript variable using
var users = #Html.Raw(Json.Encode(Model.AllUsers))
which you can then iterate over
$.each(users, function(index, item) {
// access the properties of each user
var id = item.Id;
var name = item.Name;
....
});
<script type="text/javascript">
var UsersList = #Html.Raw(Json.Encode(Model.AllUsers))
for (var i = 0; i < UsersList.length; i++) {
alert(UsersList[i].Id);
alert(UsersList[i].Name);
}
</script>
JavaScript generally is unhappy with razor components although if the above is part of an CSHTML file it will work.
The other approaches are:
Display the collection using razor #foreach ...
Pass the collection as a parameter from you webpage into a JavaScript function on some event
How are you calling this function and what does it do?
In My Case, I fixed by this way :
#for(int i=0;i<Model.AllUsers.Count;i++)
{
#: var name = '#Html.Raw(#Model.AllUsers[i].Name)';
#:alert(name);
}
I have a JObject from JSON.NET with the following:
var jOBject = {"schedule.ID" : 1, "schedule.Name" : "NameSchedule"}
The above is what I get from using Javascript to return the ID's and values of textboxes in the MVC Form in my View.
In my controller using C#, I would like to convert it into a Schedule Object that has the following Properties:
public class Schedule {
public int ID {get;set;}
public string Name {get;set;}
}
I cannot do a
Schedule sched = jsonObject.toObject<Schedule>();
because the names are slightly different as the properties on the Jobject is prepended with 'schedule'.
Is there a query or a way to do the conversion that allows me to remove the 'schedule' in the jsonObject such that I can do the simple conversion in one line?
One simple way to get it working is to use the JsonProperty attribute to specify what JSON key you want to map to a certain C# property:
public class Schedule
{
[JsonProperty("schedule.ID")]
public int ID {get;set;}
[JsonProperty("schedule.Name")]
public string Name {get;set;}
}
Then you can just use JsonConvert.DeserializeObject to deserialize your JSON into a Schedule instance:
var schedule = JsonConvert.DeserializeObject<Schedule>(json);
Example: https://dotnetfiddle.net/Nml9be
To use different key names in the JSON, you can decorate your C# class with DataContract and DataMember attributes.
[DataContract]
public class Schedule {
[DataMember("schedule.ID")]
public int ID { get; set; }
[DataMember("schedule.Name")]
public string Name { get; set; }
}
JObject scheduleObj={schedule:{"ID" : 1, "Name" : "NameSchedule"}}
JsonSerializer seria = new JsonSerializer();
Schedule oSchedule = new Schedule();
if (ScheduleObj["Schedule"] != null)
{
oSchedule = (Schedule)seria.Deserialize(new JTokenReader(ScheduleObj["Schedule"]), typeof(Schedule));
}
Here is the JSON that I want to deserialize into Dictionary using native Javascript support.
string data = "{"Symptom":[true,true,true],"Action":[true,true],"AllArea":true}";
But when I attempt to deserialize using below code
Dictionary values = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize>(data);
It gives me an error stating
"Type 'System.String' is not supported for deserialization of an array"
I am using .Net Framework 3.5. Please help me getting this done.
i guess you can not convert that to a dictionary directly... i think deserializer needs a corresponding type, with intelligible property names with type,
i think you can convert to a type, then generate your dictionary, something like:
public class MyClass
{
public List<bool> Symptom { get; set; }
public List<bool> Action { get; set; }
public bool AllArea { get; set; }
public Dictionary<string, List<bool>> getDic()
{
// this is for example, and many many different may be implement
// maybe some `reflection` for add property dynamically or ...
var oDic = new Dictionary<string, List<bool>>();
oDic.Add("Symptom", this.Symptom);
oDic.Add("Action", this.Action);
oDic.Add("AllArea", new List<bool>() { AllArea });
return oDic;
}
}
then:
string data = "{\"Symptom\":[true,true,true],\"Action\":[true,true],\"AllArea\":true}";
System.Web.Script.Serialization.JavaScriptSerializer aa = new System.Web.Script.Serialization.JavaScriptSerializer();
var o = aa.Deserialize<MyClass>(data);
var dic = o.getDic();
anyhow, it was a good question
My controller is returning an object graph to the view in json format like this
return Json(customer);
On the view my json object looks like this
{
Name: 'Joe',
Budget: { Amount: 500, Spend: 100 }
}
Which maps correctly to my customer object:
public class Customer
{
public string Name {get;set;}
public Budget Budget{get;set;}
}
public class Budget
{
public decimal Amount{get;set;}
public decimal Spend{get;set;}
}
I want to pass that same json object back to another method on the controller with this signature:
public ActionResult Method(Customer customer)
When I do this customer's name get populated but not the Budget class, which I understand why because the modelbinder is expecting this: {Name:'Joe','Budget.Amount':500,'Budget.Spend': 100}
So I have to options:
1. I can return the json object in the format it wants, but I don't know how because you can't do this:
return Json(new { Budget.Amount= 500})
I can flatten the json object on the client side. Is there plugins or methods to do this?
Here's a function that convert an object to a flat hash
function flatten(json){
var nj = {},
walk = function(j){
var jp;
for(var prop in j){
jp = j[prop];
if(jp.toString() === "[object Object]"){
walk(jp);
}else{
nj[prop] = jp;
}
}
};
walk(json);
return nj;
}
Protovis has a JavaScript flattener, available under the BSD License.
In my case we have solved it by passing additional object to the action url.
public ActionResult Method(Customer customer, [Bind(Prefix="Budget")]Budget budget)
to make this happen you have to flatten the json data (before you sent it to controller) in following way:
How to pass complex type using json to ASP.NET MVC controller