How to serialize a Dictionary in XML [duplicate] - c#

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.

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.

How to use C# JsonProperty Serialization [duplicate]

This question already has answers here:
Issue with serializing data using JSON.Net
(1 answer)
Configure Json.NET serialization settings on a class level
(1 answer)
Closed 2 years ago.
I am trying to return a class object where it will serialize the json without lowercase of the first letter of the property names. I can add the [JsonProperty{"MyField")] and that does work but is there a easier way as I have a lot of properties to do this for on the class. I don't want to set a global setting where it may break some things so just trying to see in my API best way to make sure the serialized json returns as is.
Thanks all

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);

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

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; }
}

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;}

Categories

Resources