1

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();
    }
}
AndyP
  • 527
  • 1
  • 14
  • 36

1 Answers1

1

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);
        }
    }
idz
  • 12,825
  • 1
  • 29
  • 40
  • If I need to do it via `Utf8Json` then how can we do it? – AndyP Nov 17 '20 at 20:05
  • It's in the code above... It uses Utf8Json *and* Newtonsoft.JSON just like you are doing. Or am I misunderstanding your question? – idz Nov 17 '20 at 20:18
  • Oh hang on, now I understand what you mean. Will update! – idz Nov 17 '20 at 20:25
  • yeah thats what I meant. Let me test it out. – AndyP Nov 17 '20 at 20:30
  • One last question. Is there any way that `Utf8Json.JsonSerializer` can ignore null fields while serializing in `ToString` or that is considered bad practice to do? – AndyP Nov 17 '20 at 21:35
  • I'm not sure on that one. Might be better to ask that as a separate question. – idz Nov 17 '20 at 21:43
  • Sure got it. Thanks for your help though! – AndyP Nov 17 '20 at 21:46
  • Opened a question [here](https://stackoverflow.com/questions/64883796/exclude-null-fields-while-serialization-using-utf8json-library) and no response yet. I also read the doc and couldn't find there as well so looks like maybe it is not possible to do this using `Utf8Json` library unless I am wrong here. – AndyP Nov 18 '20 at 03:07