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.
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 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 have an object in Javascript that looks like this
function MyObject(){
this.name="";
this.id=0;
this.....
}
I then stringify an array of those objects and send it to an ASP.Net web service.
At the webservice I want to unserialize the JSON string so I can deal with the data easily in C#. Then, I want to send an array of objects of the same Javascript type(same field names and everything) back to the client. The thing I'm not understanding is how to serialize say this class:
class MyObject{
public string Name;
public int ID;
}
so that the JSON is the same as the above javascript object. And also how to unserialize into the C# MyObject class.
How would I do this easily? I am using Netwonsoft.Json.
Is there some way to turn a JSON string into a List or Array of an object?
with json.net you can use the JsonPropertyAttribute to give your serialized properties a custom name:
class MyObject{
[JsonProperty(PropertyName = "name")]
public string Name;
[JsonProperty(PropertyName = "id")]
public int ID;
}
you can then serialize your object into a List<> like so:
var list = new List<MyObject>();
var o = new MyObject();
list.Add(o);
var json = JsonConvert.SerializeObject(list);
and deserialize:
// json would look like this "[{ "name":"", "id":0 }]"
var list = JsonConvert.DeserializeObject<List<MyObject>>(json);
One thing the WebMethod gives you back is a "d" wrapper which I battled with for hours to get around. My solution with the Newtonsoft/JSON.NET library is below. There might be an easier way to do this I'd be interested to know.
public class JsonContainer
{
public object d { get; set; }
}
public T Deserialize<T>(string json)
{
JsonSerializer serializer = new JsonSerializer();
JsonContainer container = (JsonContainer)serializer.Deserialize(new StringReader(json), typeof(JsonContainer));
json = container.d.ToString();
return (T)serializer.Deserialize(new StringReader(json), typeof(T));
}
You can try the DataContractJsonSerializer Rick Strahl Has a fairly good example.
You tell the serializer the type that you are serializing to and you can decorate the class properties telling them to expect a different name.
As an example:
class MyObject{
[DataMember(name="name")]
public string Name;
[DataMember(name="id")]
public int ID;
}
EDIT: Use
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
ser = new DataContractJsonSerializer(typeof(MyObject));
MyObject obj = ser.ReadObject(ms) as MyObject;
int myObjID = obj.ID;
string myObjName = obj.Name;
}