Newtonsoft JSON serialization for byte[] property [duplicate]

我与影子孤独终老i 提交于 2021-02-16 20:20:47

问题


public class MyClass
{
   public byte[] Bytes{get;set;}
}

MyClass obj = new MyClass();
obj.Bytes = new byte[]{1,22,44,55};

string s_result = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

// my s_result looks like {"Bytes":"KQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}

I want result like "Bytes":"1,22,44,55"

I did work around for this by creating one more int[] property in class like

 public class MyClass
    {
       [JsonIgnore]
       public byte[] Bytes{get;set;}
       public int[] MessageByte
        {
            get
            {
              if (this.Bytes == null)
                return null;
                int[] result = new int[this.Bytes.Length];
                for (int i = 0; i < this.Bytes.Length; i++)
                {
                    result[i] = this.Bytes[i];
                }
                return result;
            }
        }

    }

any suggestions ?


回答1:


In the docs it is declared that a Byte[] will be serialized as a Base64 encoded string. So it is working as intended.

However you need an array of numbers. I assume that you cannot simply change the byte[] to an int[] right?

Your work-around is actually the proper way of handling it, you can reduce the logic down a bit if you are interested (and using C#6 or above):

public int[] MessageBytes => Bytes?.Select(x => (int)x).ToArray() ?? new int[0];

This will "short circuit" if Bytes is null, and return an empty int array, if Bytes is not null, it will cast all the bytes to an int and then make that an array.

DotNetFiddle does not allow nuget packages in Roslyn compilers, so I cannot demonstrate the serialization. However this fiddle demonstrates the LINQ logic I just showed.

EDIT

I think the linked duplicate has a much better answer than just doing a int[], try looking into that before resorting to an int array.



来源:https://stackoverflow.com/questions/48308745/newtonsoft-json-serialization-for-byte-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!