Newtonsoft Byte []属性的JSON序列化 [英] Newtonsoft JSON serialization for byte[] property
问题描述
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="}
我想要类似字节"的结果:"1,22,44,55"
I want result like "Bytes":"1,22,44,55"
我确实通过在类之类中再创建一个int []属性来解决此问题
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;
}
}
}
有什么建议吗?
推荐答案
In the docs it is declared that a Byte[]
will be serialized as a Base64 encoded string. So it is working as intended.
但是,您需要一个数字数组.我认为您不能简单地将byte[]
更改为int[]
吗?
However you need an array of numbers. I assume that you cannot simply change the byte[]
to an int[]
right?
您的变通办法实际上是处理它的正确方法,如果您有兴趣(并且使用C#6或更高版本),则可以将逻辑降低一些:
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];
如果Bytes为null,这将短路",并返回一个空的int数组;如果Bytes不为null,它将把所有字节转换为一个int,然后将该数组制成.
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在Roslyn编译器中不允许nuget包,因此我无法演示序列化.但是这个小提琴演示了我刚刚展示的LINQ逻辑.
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.
编辑
我认为链接的重复项具有比仅做int[]
更好的答案,请尝试一下求助于int数组.
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.
这篇关于Newtonsoft Byte []属性的JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!