I'm trying to get Json.Net to serialise a property name without quote marks, and finding it difficult to locate documentation on Google. How can I do this?
It's in a very small part of a large Json render, so I'd prefer to either add a property attribute, or override the serialising method on the class.
Currently, the it renders like this:
"event_modal":
{
"href":"file.html",
"type":"full"
}
And I'm hoping to get it to render like: (href and type are without quotes)
"event_modal":
{
href:"file.html",
type:"full"
}
From the class:
public class ModalOptions
{
public object href { get; set; }
public object type { get; set; }
}
It's possible, but I advise against it as it would produce invalid JSON as Marcelo and Marc have pointed out in their comments.
Using the Json.NET library you can achieve this as follows:
[JsonObject(MemberSerialization.OptIn)]
public class ModalOptions
{
[JsonProperty]
public object href { get; set; }
[JsonProperty]
public object type { get; set; }
}
When serializing the object use the JsonSerializer type instead of the static JsonConvert type.
For example:
var options = new ModalOptions { href = "file.html", type = "full" };
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
using (var writer = new JsonTextWriter(stringWriter))
{
writer.QuoteName = false;
serializer.Serialize(writer, options);
}
var json = stringWriter.ToString();
This will produce:
{href:"file.html",type:"full"}
If you set the QuoteName property of the JsonTextWriter instance to false the object names will no longer be quoted.
You can also try a regex replace, with a substitution, which could handle any serialized object, and replace the quotes for you.
For Example:
var options = new ModalOptions { href = "file.html", type = "full" };
string jsonText = JsonConvert.SerializeObject(options);
string regexPattern = "\"([^\"]+)\":"; // the "propertyName": pattern
Console.WriteLine(Regex.Replace(jsonText, regexPattern, "$1:"));
This would produce:
{href:"file.html",type:"full"}
I built a working web example here.
Explanation of regex substitutions are here.
Related
I have model as below:
public class CustomModel
{
public string Data1 { get; set; }
public string Data2 { get; set; }
}
public class root
{
public List<CustomModel> data { get; set; }
}
My payload is as below:
List<CustomModel> cms = new List<CustomModel>();
CustomModel cm1 = new CustomModel();
cm1.Data1 = "a";
cm1.Data2 = "b";
cms.Add(cm1);
CustomModel cm2 = new CustomModel();
cm2.Data1 = "D";
cm2.Data2 = "E";
cms.Add(cm2);
BaseClass baseClass = new BaseClass();
baseClass.data = cms;
My JSON is:
var json = new JavaScriptSerializer().Serialize(baseClass);
And Result is:
{"data":[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]}
BUT I need: without the "data" property as below:
{[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]}
I tried the below function:
public static IEnumerable<object> GetPropertyValues<T>(T input)
{
return input.GetType()
.GetProperties()
.Select(p => p.GetValue(input));
}
Like
var value_only = GetPropertyValues(baseClass);
var json = new JavaScriptSerializer().Serialize(value_only);
BUT it returns [[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]]
Is there anywasy to do it other than manually adding? Please help.
Note that {[{"data1":"a","data2":"b"},{"data1":"D","data2":"E"}]} is not valid json. In Json objects, data/values are organized by (named) properties.
However, here you seem to want a (root) Json object containing a value being Json array, but that value is not associated with a Json object property, thus not being valid Json.
If you really want invalid Json, i suggest you serialize the List<CustomModel> instance instead of the root model instance, resulting in a Json array, and then manually adding the surrounding { and } to the serialized Json string, thus giving you your desired invalid Json result:
var json = new JavaScriptSerializer().Serialize(baseClass.data);
var desiredResult = "{" + json + "}";
you don't need root class (or base class you must to deside what is name. Just use
var json = new JavaScriptSerializer().Serialize(cms);
PS.
And it is time to select a modern serializer.
Is it recommended or even possible to convert Pascal Case JSON string to Camel Case JSON?
I know how to deserialize the payload to an object and then serialize it to a string again but that is not what I want at the moment.
So far I have done this:
JsonSerializerOptions jsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase};
var pascalPayload = "{\"Id\":\"1\",\"Type\":\"Confectionary\"}";
var camelCasePayload = JsonSerializer.Serialize(pascalPayload, jsonOptions)
The issue I see here is that it contains the following characters and I wasn't expecting that and also my properties are not serialized to camelcase.
For example
{\u0022Id:\u00221\u0022,....
Am I missing something from the serialisation options because I was expecting this as the output:
"{"id":"1","type":"Confectionary"}";
You are passing a string to Serialize and not an object. So you are effectively serializing a string which already is json into a string value....
You need to pass an object like this:
First declare a class:
public class MyPayload
{
public string Id { get; set; }
public string Type { get; set; }
}
Then your code:
JsonSerializerOptions jsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase};
//notice we create an instance and pass that to Serialize
var pascalPayload = new MyPayload { Id = "1", Type = "Confectionary"};
var camelCasePayload = JsonSerializer.Serialize(pascalPayload, jsonOptions);
There is no way around it using JsonSerializer.... If you dont want to use an object then you need to manipulate the string yourself.
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;
}
I'm trying to get Json.Net to serialise a property name without quote marks, and finding it difficult to locate documentation on Google. How can I do this?
It's in a very small part of a large Json render, so I'd prefer to either add a property attribute, or override the serialising method on the class.
Currently, the it renders like this:
"event_modal":
{
"href":"file.html",
"type":"full"
}
And I'm hoping to get it to render like: (href and type are without quotes)
"event_modal":
{
href:"file.html",
type:"full"
}
From the class:
public class ModalOptions
{
public object href { get; set; }
public object type { get; set; }
}
It's possible, but I advise against it as it would produce invalid JSON as Marcelo and Marc have pointed out in their comments.
Using the Json.NET library you can achieve this as follows:
[JsonObject(MemberSerialization.OptIn)]
public class ModalOptions
{
[JsonProperty]
public object href { get; set; }
[JsonProperty]
public object type { get; set; }
}
When serializing the object use the JsonSerializer type instead of the static JsonConvert type.
For example:
var options = new ModalOptions { href = "file.html", type = "full" };
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
using (var writer = new JsonTextWriter(stringWriter))
{
writer.QuoteName = false;
serializer.Serialize(writer, options);
}
var json = stringWriter.ToString();
This will produce:
{href:"file.html",type:"full"}
If you set the QuoteName property of the JsonTextWriter instance to false the object names will no longer be quoted.
You can also try a regex replace, with a substitution, which could handle any serialized object, and replace the quotes for you.
For Example:
var options = new ModalOptions { href = "file.html", type = "full" };
string jsonText = JsonConvert.SerializeObject(options);
string regexPattern = "\"([^\"]+)\":"; // the "propertyName": pattern
Console.WriteLine(Regex.Replace(jsonText, regexPattern, "$1:"));
This would produce:
{href:"file.html",type:"full"}
I built a working web example here.
Explanation of regex substitutions are here.
I'm trying to get Json.Net to serialise a property name without quote marks, and finding it difficult to locate documentation on Google. How can I do this?
It's in a very small part of a large Json render, so I'd prefer to either add a property attribute, or override the serialising method on the class.
Currently, the it renders like this:
"event_modal":
{
"href":"file.html",
"type":"full"
}
And I'm hoping to get it to render like: (href and type are without quotes)
"event_modal":
{
href:"file.html",
type:"full"
}
From the class:
public class ModalOptions
{
public object href { get; set; }
public object type { get; set; }
}
It's possible, but I advise against it as it would produce invalid JSON as Marcelo and Marc have pointed out in their comments.
Using the Json.NET library you can achieve this as follows:
[JsonObject(MemberSerialization.OptIn)]
public class ModalOptions
{
[JsonProperty]
public object href { get; set; }
[JsonProperty]
public object type { get; set; }
}
When serializing the object use the JsonSerializer type instead of the static JsonConvert type.
For example:
var options = new ModalOptions { href = "file.html", type = "full" };
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
using (var writer = new JsonTextWriter(stringWriter))
{
writer.QuoteName = false;
serializer.Serialize(writer, options);
}
var json = stringWriter.ToString();
This will produce:
{href:"file.html",type:"full"}
If you set the QuoteName property of the JsonTextWriter instance to false the object names will no longer be quoted.
You can also try a regex replace, with a substitution, which could handle any serialized object, and replace the quotes for you.
For Example:
var options = new ModalOptions { href = "file.html", type = "full" };
string jsonText = JsonConvert.SerializeObject(options);
string regexPattern = "\"([^\"]+)\":"; // the "propertyName": pattern
Console.WriteLine(Regex.Replace(jsonText, regexPattern, "$1:"));
This would produce:
{href:"file.html",type:"full"}
I built a working web example here.
Explanation of regex substitutions are here.