Search code examples
c#jsonjson.netutf8json

How to serialize json with fields name as datamember only?


I have a POCO like this:

public class Process
{
    public Process() { }

    [DataMember(Name = "lang_code")]
    public string LCode { get; set; }

    [DataMember(Name = "data_currency")]
    public string Currency { get; set; }

    [DataMember(Name = "country_code")]
    public string CCode { get; set; }

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}

Now when I serialize my POCO I get json back like this which has field name:

{"LCode":"en-US","Currency":"USD","CCode":"IN"}

Is there any way to get it the way DataMember fields are after serializing POCO. Something like below:

{"lang_code":"en-US","data_currency":"USD","country_code":"IN"}

Below is the code we have:

ProcessStr = ExtractHeader(headers, PROCESS_HEADER);
Console.WriteLine(ProcessStr);
if (!string.IsNullOrWhiteSpace(ProcessStr))
{
    Process = DeserializeJson<Process>(ProcessStr);
    if (Process != null && !string.IsNullOrWhiteSpace(Process.Gold))
    {
        Process.Gold = HttpUtility.HtmlEncode(Process.Gold);
    }
    ProcessStr = Process.ToString();
    Console.WriteLine(ProcessStr);
}

private T DeserializeJson<T>(string str) where T : new()
{
    try
    {
        return Utf8Json.JsonSerializer.Deserialize<T>(str);
    }
    catch (Exception e)
    {
        return new T();
    }
}

Solution

  • It looks like you are using two different packages, Newtonsoft.Json to serialize and Utf8Json to deserialize. They use different annotations. You can get it to work, but it might be simpler to choose one or the other.

    Newtonsoft.Json uses the JsonProperty attribute whereas Utf8Json uses the DataMember one.

    using System;
    using System.Diagnostics;
    using System.Runtime.Serialization;
    using Newtonsoft.Json;
    using Utf8Json;
    
    namespace JSONPropertyTest
    {
        public class Process
        {
            public Process() { }
    
            [JsonProperty("lang_code")]
            [DataMember(Name = "lang_code")]
            public string LCode { get; set; }
    
            [JsonProperty("data_currency")]
            [DataMember(Name = "data_currency")]
            public string Currency { get; set; }
    
            [JsonProperty("country_code")]
            [DataMember(Name = "country_code")]
            public string CCode { get; set; }
    
            public override string ToString()
            {
                return JsonConvert.SerializeObject(this);
            }
        }
    
        class Program
        {
            static private T DeserializeJson<T>(string str) where T : new()
            {
                try
                {
                    return Utf8Json.JsonSerializer.Deserialize<T>(str);
                }
                catch (Exception e)
                {
                    return new T();
                }
            }
    
            static void Main(string[] args)
            {
                var test = new Process { LCode = "en-US",Currency = "USD", CCode = "IN" };
                var json = test.ToString();
    
                Console.WriteLine($"serialized={test}");
                var deserialized = DeserializeJson<Process>(json);
                Debug.Assert(test.CCode == deserialized.CCode);
                Debug.Assert(test.LCode == deserialized.LCode);
                Debug.Assert(test.Currency == deserialized.Currency);
                Console.WriteLine($"deserialized={deserialized}");
            }
        }
    }
    

    To just use Utf8Json you need to update your ToString method, which is the only one in the code you've shown that relies on Newtonsoft.Json. That would look like this:

        public class Process
        {
            public Process() { }
    
            [DataMember(Name = "lang_code")]
            public string LCode { get; set; }
    
            [DataMember(Name = "data_currency")]
            public string Currency { get; set; }
    
            [DataMember(Name = "country_code")]
            public string CCode { get; set; }
    
            public override string ToString()
            {
                return Utf8Json.JsonSerializer.ToJsonString(this);
            }
        }