Can I map a JSON element "#somename"? [duplicate] - c#

This question already has answers here:
.NET NewtonSoft JSON deserialize map to a different property name
(6 answers)
Closed 3 years ago.
I’m targeting .net framework 4.7 with a winforms application.
I started by following this article https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient so I am using DataContractJsonSerializer.
I’m trying to learn about a REST interface that returns JSON -
{"Resource":
{"#attributes":
{"name":"Asset",
"resourceId":"Asset",
"type":"Resource"
}
}
}
I used netwonsoft.json 12.0.2 to paste the JSON as classes. It ignores the ‘#’ character and creates a member “attributes” in class “Resource” with type “Attributes” .
When DataContractJsonSerializer attempts to deserialise the JSON it skips the #attribute element, I presume because it does not match the class name.
Is there a way to map the element #attributes to my attributes member / class?
I have tried adding [DataMember(Name = "#attributes")] on the attributes member of the Resource class and a [DataContract(Name = "#attributes")] on the Attributes class but still the element appears to be skipped (attributes member of Resource is null).

Yes, use JsonProperty
public class MyClass
{
[JsonProperty("#attributes")]
public string attributes { get; set; }
}

Related

How to make a property visible (scope, access modifier) only by XmlSerializer in C#? [duplicate]

This question already has answers here:
How can I serialize internal classes using XmlSerializer?
(5 answers)
c#: how to hide a field which is used only for XML serialization retrocompatibility?
(3 answers)
Closed 2 years ago.
I would like to make some property of a class visisble (scope, access modifier) only by the XML serializer.
I'm not sure about the best way to hide some properties from the consumers of a class without over engineering.
Let's see an exemple:
public class MyClass
{
[XmlIgnore]
public Version Version { get; set; }
/// <summary>
/// Do not used. This is a dummy property for XML serialization.
/// </summary>
[XmlAttribute(AttributeName = nameof(Version))]
public string XmlVersion
{
get => Version.ToString();
set => Version = new Version(value);
}
}
This kind of code allows me to use a class which is not designed to be serialized (System.Version isn't because its properties are readonly).
I would like that the consumers of my class see only Version but not the XmlVersion property.
Edit : If it's possible, I'd like those properties to be hidden even in the project where the class is so my co-worker won't use those dummy properties too.
I know I can use ObsoleteAttribute to give information why they should be avoided but those properties will still be usable which isn't the behavior I'm looking for.

JsonProperty on C# Records in Constructor [duplicate]

This question already has answers here:
How do I target attributes for a record class?
(2 answers)
Closed 1 year ago.
With the new C# record types in C# 9 i'd like to know wheter it is possible (for serialization) to set the JsonPropertyAttribute from Newtonsoft.Json on the constructor parameter.
It doesn't seem to work out of the box.
MWE:
using System;
using Newtonsoft.Json;
Console.WriteLine(JsonConvert.SerializeObject(new Something("something")));
record Something([JsonProperty("hello")] string world) {}
Output:
{"world":"something"}
Expected output:
{"hello":"something"}
is there an easy way to make it work like this? or do we have to revert back to the property style with a real constructor?
internal record Something
{
public Something(string world) { World = world; }
[JsonProperty("hello")] public string World { get; }
}
Per the docs:
Attributes can be applied to the synthesized auto-property and its backing field by using property: or field: targets for attributes syntactically applied to the corresponding record parameter.
So you want
record Something([property:JsonProperty("hello")] string world) {}
Without the property: qualifier, the attribute ends up on the parameter of the generated constructor (which is useful in other scenarios, like nullability).

How to indicate member's constructor in a collection during deserialization by Json.net? [duplicate]

This question already has answers here:
How to programmatically choose a constructor during deserialization?
(5 answers)
Closed 3 years ago.
I wish deserialize list by json.net. The inkpoint has a constructor with parameters. The json.net seems does not automatic use the inkpoint constructor.
I think I should use the IContractResolver Interface or JsonConverter, to indicate use the inkpoint's constructor with parameters. But I just know how to deserialize a Object like this, do not know how to use them in a collection.
Just use the JsonConstructor attribute
[JsonConstructor]
public Model(int? id, string name, string description)
{
...
}
Just make sure the param names match the json
For collections, as long as the json represents an array of objects you have a model for, you can just do something like
List<Model> models= JsonConvert.DeserializeObject<List<Model>>(json);

C# Data Deserialization from JSON string - Variable routing [duplicate]

This question already has answers here:
.NET NewtonSoft JSON deserialize map to a different property name
(6 answers)
Closed 4 years ago.
I am consuming a simple REST API. The way I usually do this from my .Net environment is to use a HttpClient and just use Newstonsoft JSON.NET to deserialize the JSON response back into a class I have created.
I usually just create my variables with the same name as the JSON variable so it can map and be deserialized correctly.
However the variables in the current API I am consuming just do not make that much sense so I am wondering if it is at possible to have something like the below so that I can name my class variables correctly but still have the deserialization map back.
[Serializable(Name="param1")]
public string CompanyName { get; set; }
Use:
[JsonProperty("param1")]
public string CompanyName {get; set;}
Or:
[JsonProperty(PropertyName="param1")]
public string CompanyName {get; set;}

How to serialize a Dictionary in XML [duplicate]

This question already has answers here:
How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?
(10 answers)
Closed 8 years ago.
I'm trying to send a XML based on this entity :
[XmlElement]
public decimal Price { get; set; }
[XmlElement]
public Dictionary<string, string> Data{get; set;}
Before the addition of the latest parameter, there was no problem but the addition of the Dictionary causes trouble.
The Exception is :
Error : There was an error reflecting type 'Project.Entities.Offers'.
Here is the Serializer and the line that cause the problem
The XmlSerializer is doing an Exception
public string Serialize<T>()
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
...
}
Is it a solution to that problem? a workaround?
Thanks to help me
Dictionary<TKey,TValue> is not marked serializeable. The reasoning for this is you can not enforce the uniqueness constraints while the dictionary is in XML form, there is nothing from stopping me from doing something like
<Dictionary>
<DictionaryElement Key="1" Value="Foo"/>
<DictionaryElement Key="1" Value="Bar"/>
</Dictionary>
However people usually write wrappers to make a dictionary serializeable, but you will need to decide if it will either silently skip duplicate keys or throw an exception on duplicate keys.

Categories

Resources