DisplayName attribute is ignored while json conversion - json

I have a class as below
public class Person
{
public string Name { get; set; }
[DisplayName ("Please Enter Your Age")]
public int Age { get; set; }
public string Sex { get; set; }
}
I serialized this object to Json using json() of MVC3, but the DisplayName attribute is ignored. I get the json as
"*{"Name":"Person Name","**Age**":28,"Sex":"Male"}*"
Actually i was expecting
"*{"Name":"Person Name","**Please Enter Your Age**":28,"Sex":"Male"}*"
Code converts the object to json
[HttpGet]
public JsonResult JsonTest()
{
Person person = new Person();
person.Age = 28;
person.Name = "Person Name";
person.Sex = "Male";
return (Json(person, JsonRequestBehavior.AllowGet));
}
Any help would be appreciated!!!

You can use the DataContractJsonSerializer to give different names to your properties by using the [DataMember(Name = "myOwnName")] data annotation. Or write your own serializer.
Example can be found here.

Internally the Json method uses the JavaScriptSerializer class to serialize the class into a JSON string. It doesn't allow you to change property names. I guess you will have to roll your own JSON serialization routine. The question is: why do you need that?

Related

System.Text.Json.JsonSerializer.Deserialize returning object with all fields null in .Net Core 3.1 [duplicate]

I am converting my newtonsoft implementation to new JSON library in .net core 3.0. I have the following code
public static bool IsValidJson(string json)
{
try
{
JObject.Parse(json);
return true;
}
catch (Exception ex)
{
Logger.ErrorFormat("Invalid Json Received {0}", json);
Logger.Fatal(ex.Message);
return false;
}
}
I am not able to find any equivalent for JObject.Parse(json);
Also what will be the attribute JsonProperty equivalent
public class ResponseJson
{
[JsonProperty(PropertyName = "status")]
public bool Status { get; set; }
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
[JsonProperty(PropertyName = "Log_id")]
public string LogId { get; set; }
[JsonProperty(PropertyName = "Log_status")]
public string LogStatus { get; set; }
public string FailureReason { get; set; }
}
One more thing i will be looking for the equivalent of Formating.None.
You are asking a few questions here:
I am not able to find any equivalent for JObject.Parse(json);
You can use JsonDocument to parse and examine any JSON, starting with its RootElement. The root element is of type JsonElement which represents any JSON value (primitive or not) and corresponds to Newtonsoft's JToken.
But do take note of this documentation remark:
This class utilizes resources from pooled memory to minimize the impact of the garbage collector (GC) in high-usage scenarios. Failure to properly dispose this object will result in the memory not being returned to the pool, which will increase GC impact across various parts of the framework.
When you need to use a JsonElement outside the lifetime of its document, you must clone it:
Gets a JsonElement that can be safely stored beyond the lifetime of the original JsonDocument.
Also note that JsonDocument is currently read-only and does not provide an API for creating or modifying JSON. There is an open issue Issue #39922: Writable Json DOM tracking this.
An example of use is as follows:
//https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations
using var doc = JsonDocument.Parse(json);
//Print the property names.
var names = doc.RootElement.EnumerateObject().Select(p => p.Name);
Console.WriteLine("Property names: {0}", string.Join(",", names)); // Property names: status,message,Log_id,Log_status,FailureReason
//Re-serialize with indentation.
using var ms = new MemoryStream();
using (var writer = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
doc.WriteTo(writer);
}
var json2 = Encoding.UTF8.GetString(ms.GetBuffer(), 0, checked((int)ms.Length));
Console.WriteLine(json2);
Also what will be the attribute JsonProperty equivalent?
Attributes that can control JsonSerializer are placed in the System.Text.Json.Serialization namespace and inherit from an abstract base class JsonAttribute. Unlike JsonProperty, there is no omnibus attribute that can control all aspects of property serialization. Instead there are specific attributes to control specific aspects.
As of .NET Core 3 these include:
[JsonPropertyNameAttribute(string)]:
Specifies the property name that is present in the JSON when serializing and deserializing. This overrides any naming policy specified by JsonNamingPolicy.
This is attribute you want to use to control the serialized names of your ResponseJson class:
public class ResponseJson
{
[JsonPropertyName("status")]
public bool Status { get; set; }
[JsonPropertyName("message")]
public string Message { get; set; }
[JsonPropertyName("Log_id")]
public string LogId { get; set; }
[JsonPropertyName("Log_status")]
public string LogStatus { get; set; }
public string FailureReason { get; set; }
}
[JsonConverterAttribute(Type)]:
When placed on a type, the specified converter will be used unless a compatible converter is added to the JsonSerializerOptions.Converters collection or there is another JsonConverterAttribute on a property of the same type.
Note that the documented priority of converters -- Attribute on property, then the Converters collection in options, then the Attribute on type -- differs from the documented order for Newtonsoft converters, which is the JsonConverter defined by attribute on a member, then the JsonConverter defined by an attribute on a class, and finally any converters passed to the JsonSerializer.
[JsonExtensionDataAttribute] - corresponds to Newtonsoft's [JsonExtensionData].
[JsonIgnoreAttribute] - corresponds to Newtonsoft's [JsonIgnore].
When writing JSON via Utf8JsonWriter, indentation can be controlled by setting JsonWriterOptions.Indented to true or false.
When serializing to JSON via JsonSerializer.Serialize, indentation can be controlled by setting JsonSerializerOptions.WriteIndented to true or false.
Demo fiddle here showing serialization with JsonSerializer and parsing with JsonDocument.
This link should get you going, snippets of which I copied below.
https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/
WeatherForecast Deserialize(string json)
{
var options = new JsonSerializerOptions
{
AllowTrailingCommas = true
};
return JsonSerializer.Parse<WeatherForecast>(json, options);
}
class WeatherForecast {
public DateTimeOffset Date { get; set; }
// Always in Celsius.
[JsonPropertyName("temp")]
public int TemperatureC { get; set; }
public string Summary { get; set; }
// Don't serialize this property.
[JsonIgnore]
public bool IsHot => TemperatureC >= 30;
}

Convert JSON string to simple object with json.net

I am using GSON on my client to stringy an object:
Gson gson = new Gson();
String data = gson.toJson(deviceInfo);
now I receive this in a header of the http request. I now need to on my server convert it back into the object. I am not parsing it as a param so the modelbinder wont just do it for me. If there is a way to manually use to model binder. then maybe that is an option as well.
How can I do this with json.net ?
basically I want the equivalent of: gson.fromJson(json, classOfT)
The equivalent of gson.fromJson(json, classOfT) in json.net is
JsonConvert.DeserializeObject<T>()
Example:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);

Very simple attempt to deserialize JSON with JSON.NET does not work

I get the error below... Something is very wrong :( any ideas? (This is in a Windows Phone 8 app)
An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.DLL but was not handled in user code
And the code is
string responseBody = #" {""HighScoreId"":1,""Name"":""Debra Garcia"",""Score"":2.23},{""HighScoreId"":2,""Name"":""Thorsten Weinrich"",""Score"":2.65}";
GlobalHighScore s = JsonConvert.DeserializeObject<GlobalHighScore>(responseBody);
and the class is
public class GlobalHighScore
{
public int HighScoreId { get; set; }
public string Name { get; set; }
public double Score { get; set; }
}
Your JSON has more than one object, and neither are in an array. You either need to remove one of the objects from the JSON or add them to an array and deserialize them properly:
string responseBody =
#"[
{""HighScoreId"":1,""Name"":""Debra Garcia"",""Score"":2.23},
{""HighScoreId"":2,""Name"":""Thorsten Weinrich"",""Score"":2.65}
]";
var highScores =
JsonConvert.DeserializeObject<List<GlobalHighScore>>(responseBody);

How to omit Get only properties in servicestack json serializer?

I have an object which I am de-serializing using ToJson<>() method from ServiceStack.Text namespace.
How to omit all the GET only propeties during serialization? Is there any attribute like [Ignore] or something that I can decorate my properties with, so that they can be omitted?
Thanks
ServiceStack's Text serializers follows .NET's DataContract serializer behavior, which means you can ignore data members by using the opt-out [IgnoreDataMember] attribute
public class Poco
{
public int Id { get; set; }
public string Name { get; set; }
[IgnoreDataMember]
public string IsIgnored { get; set; }
}
An opt-in alternative is to decorate every property you want serialized with [DataMember]. The remaining properties aren't serialized, e.g:
[DataContract]
public class Poco
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
public string IsIgnored { get; set; }
}
Finally there's also a non-intrusive option that doesn't require attributes, e.g:
JsConfig<Poco>.ExcludePropertyNames = new [] { "IsIgnored" };
Dynamically specifying properties that should be serialized
ServiceStack's Serializers also supports dynamically controlling serialization by providing conventionally named ShouldSerialize({PropertyName}) methods to indicate whether a property should be serialized or not, e.g:
public class Poco
{
public int Id { get; set; }
public string Name { get; set; }
public string IsIgnored { get; set; }
public bool? ShouldSerialize(string fieldName)
{
return fieldName == "IsIgnored";
}
}
More examples in ConditionalSerializationTests.cs
For nullable members, you also have the ability to set it to null before serializing.
This is particularly useful if you want to create a single view/api model that is re-used for several API calls. The service can touch it up before setting it on the response object.
Example:
public SignInPostResponse Post(SignInPost request)
{
UserAuthentication auth = _userService.SignIn(request.Domain, true, request.Username, request.Password);
// Map domain model ojbect to API model object. These classes are used with several API calls.
var webAuth = Map<WebUserAuthentication>(auth);
// Exmaple: Clear a property that I don't want to return for this API call... for whatever reason.
webAuth.AuthenticationType = null;
var response = new SignInPostResponse { Results = webAuth };
return response;
}
I do wish there was a way to dynamically control the serialization of all members (including non-nullable) on a per endpoint fashion.

Monotouch: Deserialize JSON from MVC to Montouch

In my test vb.net MVC web app, I have this json....
Public Class Person
Public Property Name As String
Public Property Age As Byte
Public Sub New(name As String, age As Byte)
Me.Name = name
Me.Age = age
End Sub
End Class
Function GetPerson() As JsonResult
Dim p As New Person("John Doe", 50)
Return Json(p, JsonRequestBehavior.AllowGet)
End Function
And in Monotouch I've got this...
JsonObject j;
Uri address = new Uri("http://mysite/home/GetPerson");
HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create (address);
using (HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse ()) {
Stream s = httpRes.GetResponseStream ();
j = (JsonObject)JsonObject.Load (s);
}
And this class...
Public Class Person {
Public string Name { get; set; }
Public byte Age { get; set; }
}
How do I parse the JsonObject j into class of Person? .. I hoped for something like Person p = (Person)j.value;
Thanks!
Mojo
First, I would use int for Age. But assuming a JSON Structure like:
{
"Name" : "John Doe",
"Age" : 100,
}
If you wanted to use the baked in System.Json stuff:
var person = new Person()
var obj = JsonObject.Parse(json);
person.Name = obj["Name"].ToString();
person.Age = (int)obj["Age"];
I would HIGHLY recommend using ServiceStack.Text though, it's a highly optimized extremely fast library for consuming JSON with compatibility with both MonoTouch and Mono for Android...out of the box!
You can check out the the API for consuming JSON with ServiceStack here.
Even if this question is now old, here is the solution I use.
With MonoTouch, you can use .net Json serialization mechanism based on DataContract.
[DataContract]
Public Class Person {
[DataMember]
Public string Name { get; set; }
[DataMember]
Public byte Age { get; set; }
}
and use the DataContractJsonSerializer (found in System.Runtime.Serialization.Json)
Stream stream = httpRes.GetResponseStream ();
DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof(Person));
Person person = (Person)jsSerializer.ReadObject(stream);
This way, the code is WCF compliant and work flawless on ms.net platform, mono and monotouch.