我遇到了有关将结构序列化为 JSON 的问题。所以,我有一个结构“坐标”
namespace CoordinatesNameSpace
{
public struct Coordinates
{
public Coordinates(string key, string x, string y, string z)
{
this.key = key;
this.x = x;
this.y = y;
this.z = z;
}
public string key;
public string x;
public string y;
public string z;
public override string ToString()
{
return $"{key} {this.x} {this.y} {this.z}";
}
}
}
所有属性都是公共的,所以我期望 json 序列化器将返回我 { "key": "v", "x": "0.12331212" ... },但它只返回一个空对象。
using CoordinatesNameSpace;
namespace ObjToJSON
{
class Program
{
static void Main(string[] args)
{
List<Coordinates> parsedCoordinatesList = new List<Coordinates>();
Coordinates _c;
_c.key = splitted[0]; // "v"
_c.x = splitted[1]; // "1.324394"
_c.y = splitted[2]; // "-0.219625"
_c.z = splitted[3]; // "-0.422554"
parsedCoordinatesList.Add(_c);
// returns an [{}, {}, {} ...]
//string json = JsonSerializer.Serialize<List<Coordinates>>(parsedCoordinatesList);
// returns {}
string json = JsonSerializer.Serialize<Coordinates>(parsedCoordinatesList[0]);
有人可以向我解释一下 - 为什么这样做以及如何使其正确序列化吗?
It seems https://github.com/dotnet/runtime/issues/876目前System.Text.Json
不支持序列化字段。将字段更改为属性,一切都应该正常:
public struct Coordinates
{
public Coordinates(string key, string x, string y, string z)
{
this.key = key;
this.x = x;
this.y = y;
this.z = z;
}
public string key { get; set; }
public string x { get; set; }
public string y { get; set; }
public string z { get; set; }
public override string ToString()
{
return $"{key} {this.x} {this.y} {this.z}";
}
}
也来自docs https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-core-3-1#deserialization-behavior:
序列化行为:
...
UPD
Since 可以包含 .NET 5 字段 https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-5-0#include-fields要么通过JsonSerializerOptions.IncludeFields
全局设置或通过JsonIncludeAttribute
.
public struct Coordinates
{
public Coordinates(string key, string x, string y, string z)
{
this.key = key;
this.x = x;
this.y = y;
this.z = z;
}
[JsonInclude]
public string key;
[JsonInclude]
public string x;
[JsonInclude]
public string y;
[JsonInclude]
public string z;
public override string ToString()
{
return $"{key} {this.x} {this.y} {this.z}";
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)