mgholam / fastJSON

Smallest, fastest polymorphic JSON serializer
https://www.codeproject.com/Articles/159450/fastJSON-Smallest-Fastest-Polymorphic-JSON-Seriali
MIT License
478 stars 148 forks source link

Mapping Json Keys to Class Properties #117

Closed selo-dev closed 3 years ago

selo-dev commented 3 years ago

Hello, I'm trying to use fastJSON for a document that has a "-" character in its key name: { „my-key“: „…“ }

Character "-" is not allowed in property names in c#. How can I deserialize to the next structure with renaming to the property "MyKey"

Class Root { Public string MyKey { get; set;} }

Thanks for the answer.

mgholam commented 3 years ago

You can use DataMember attributes:

Class Root
{
    [DataMember(Name = "my-key")]
    public string MyKey { get; set;}
}
selo-dev commented 3 years ago

I forgot to say that I am using fastJSON 3.5 and the classes from "System.Runtime.Serialization.dll" are not available for me

mgholam commented 3 years ago

Currently you can't on v3.5, try upgrading your EXE and fastJSON to v4.0 (all else should work with v3.5 DLLs)

selo-dev commented 3 years ago

I cannot use the new runtime because this is used in "sql clr" in Sql Server 2008 r2. However, I use the following construct for this and it works for me: String jsonText = fastJSON.JSON.ToJSON(myRootInstance).Replace("\"MyKey\"", "\"my-key\"");

Maybe you can add another mapping method in the next versions

mgholam commented 3 years ago

Try v2.3.3 I've added fastJSON.DataMember and let me know

selo-dev commented 3 years ago

Great! It works!