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));
}
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";
}
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.
I've been trying to get ng-table(angular directive) work with a web api (ASP.NET MVC). I can load and page the data but the sorting or filtering won't work.
The weird thing is that the sorting or filtering will look like this in the URL:
http://localhost:46278/api/rating?count=10&filter%5Brating.name%5D=fs&page=1&sorting%5Brating.description%5D=asc
If you would "format" it, it would look like this:
filter[rating.name] = fs
sorting[rating.description] = asc
I tried to get them with a string array or a dictionary (KeyValuePair)
But I can't get the values. So I can never filter or sort the data.
I hope you can give me some advice! I appreciate your help!
I wrote a helper class to deal with this. The URL isn't formatted in a way WebAPI expects, so couldn't get the ModelBinder to parse it automatically.
From your controller, call the helpers and provide the entire URL:
// Parse sortings
var sortings = TableHelpers.ParseSortings(Request.RequestUri).ToList();
// Parse filters
var filters = TableHelpers.ParseFilters(Request.RequestUri).ToList();
And the helper class
public static class TableHelpers
{
public static IEnumerable<TableSorting> ParseSortings(Uri requestUri)
{
var regex = new Regex("sorting%5B(.+?)%5D=(asc|desc)");
var matches = regex.Matches(requestUri.AbsoluteUri);
return from Match match in matches
select new TableSorting {Field = match.Groups[1].Value, Order = match.Groups[2].Value};
}
public static IEnumerable<TableFilter> ParseFilters(Uri requestUri)
{
var regex = new Regex("filter%5B(.+?)%5D=(.+?)(?:&|\\z)");
var matches = regex.Matches(requestUri.AbsoluteUri);
return from Match match in matches
select new TableFilter {Field = match.Groups[1].Value, Value = match.Groups[2].Value};
}
}
public class TableSorting
{
public string Field { get; set; }
public string Order { get; set; }
}
public class TableFilter
{
public string Field { get; set; }
public string Value { get; set; }
}
are you asking about directive syntax or your api?
in ng-table directive, insert in <td> tag sorting or/and filtering attrs, like:
<td width="10%" data-title="'NUM'|translate" filter="{ 'num': 'text' }" sortable="'num'"><span>{{item.num}}</span></td>
I am new in C# and would like to know if it's possible to create an array in C# like following:
rates[0]['logic_id'] = 12;
rates[0]['line_id'] = ""
rates[0]['rate'] = rateVal;
rates[0]['changed'] = isChanged;
rates[1]['logic_id'] = 13;
rates[1]['line_id'] = ""
rates[1]['rate'] = secvalue;
rates[1]['changed'] = isChanged;
Can I create rates array in C# with such values?
EDIT:
My goal is to send rates array to a specific Web API service that is running with PHP. They accept only array with abovementioned structure. That's why I want to achieve that.
The best approach here would be to create a Rate class that is held in a List<Rate>().
public class Rate
{
public int LogicId { get; set; }
public string LineId { get; set; }
public decimal Rate { get; set; }
public bool IsChanged { get; set; }
}
public void Populate()
{
var rates = new List<Rate>();
var rate = new Rate();
rate.LogicId = 12;
rate.LineId = string.Empty;
rate.Rate = 0;
rate.IsChanged = true;
rates.Add(rate);
}
To access the values, you can loop through them:
foreach(var rate in rates)
{
//Do something with the object, like writing some values to the Console
Console.WriteLine(rate.LogicId);
Console.WriteLine(rate.Rate);
}
You could solve it using arrays, but it's someway outdated the approach.
My suggestion is that you should use a List<Dictionary<string, object>>:
var data = new List<Dictionary<string, object>>();
data.Add(new Dictionary<string, object>());
data[0].Add("rate", rateVal);
And later you can access it like JavaScript using dictionary's indexer:
var rate = data[0]["rate"];
Update
OP said:
My goal is to send rates array to a specific Web API service that is
running with PHP. They accept only array with abovementioned
structure. That's why I want to achieve that.
No problem. If you serialize that list of dictionaries using JSON.NET, you can produce a JSON which will contain an array of objects:
[{ "rate": 2 }, { "rate": 338 }]
Actually, .NET List<T> is serialized as a JSON array and a Dictionary<TKey, TValue> is serialized as a JSON object, or in other words, as an associative array.
This can depend on your specific neeeds, mut maybe you just want a list of objects
first create a class:
class Rate
{
public int LoginId { get; set; }
public int? LineId { get; set; }
public decimal RateValue { get; set; }
public bool IsChanged { get; set; }
}
Then, in any method you want, just use:
List<Rate> Rates = new List<Rate>();
Rates.Add(new Rate() {LoginId = 1, LineId = null, RateValue = Rateval, IsChanged = false});
Rates.Add(new Rate() {LoginId = 13, LineId = null, RateValue = SecVal, IsChanged = false});
EDIT
My apologies for the terrible answer, edited to account for the errors
public struct Rate
{
public int LoginId ;
public int LineId ;
public double RateValue ;
public bool IsChanged;
}
public static void makelist()
{
List<Rate> Rates = new List<Rate>();
Rates.Add(new Rate() {LoginId = 1, LineId = null, RateValue = Rateval,IsChanged = false});
}
This method will only hold data, and not hold methods like a class.
With the data types defined in the struct, memory usage stays low as its only purpose is to store data. This is a midway between a variable and a class.
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