問題描述
我仔細閱讀了文檔、StackOverflow 等,似乎找不到這個...
I've pored through the docs, StackOverflow, etc., can't seem to find this...
我想做的是將一個簡單的值類型的對象序列化/反序列化為一個值,而不是一個對象,如下所示:
What I want to do is serialize/deserialize a simple value-type of object as a value, not an object, as so:
public class IPAddress
{
byte[] bytes;
public override string ToString() {... etc.
}
public class SomeOuterObject
{
string stringValue;
IPAddress ipValue;
}
IPAddress ip = new IPAddress("192.168.1.2");
var obj = new SomeOuterObject() {stringValue = "Some String", ipValue = ip};
string json = JsonConverter.SerializeObject(obj);
我想要的是讓 json 像這樣序列化:
What I want is for the json to serialize like this:
// json = {"someString":"Some String","ipValue":"192.168.1.2"} <- value serialized as value, not subobject
不是 ip 成為嵌套對象的地方,例如:
Not where the ip becomes a nested object, ex:
// json = {"someString":"Some String","ipValue":{"value":"192.168.1.2"}}
有人知道怎么做嗎?謝謝!(P.S. 我在一個龐大的遺留 .NET 代碼庫上使用 Json 序列化,所以我無法真正更改任何現有類型,但我可以擴充/分解/裝飾它們以促進 Json 序列化.)
Does anyone know how to do this? Thanks! (P.S. I am bolting Json serialization on a large hairy legacy .NET codebase, so I can't really change any existing types, but I can augment/factor/decorate them to facilitate Json serialization.)
推薦答案
您可以使用 IPAddress
類的自定義 JsonConverter
來處理這個問題.這是您需要的代碼:
You can handle this using a custom JsonConverter
for the IPAddress
class. Here is the code you would need:
public class IPAddressConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(IPAddress));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return new IPAddress(JToken.Load(reader).ToString());
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken.FromObject(value.ToString()).WriteTo(writer);
}
}
然后,將 [JsonConverter]
屬性添加到您的 IPAddress
類中,您就可以開始了:
Then, add a [JsonConverter]
attribute to your IPAddress
class and you're ready to go:
[JsonConverter(typeof(IPAddressConverter))]
public class IPAddress
{
byte[] bytes;
public IPAddress(string address)
{
bytes = address.Split('.').Select(s => byte.Parse(s)).ToArray();
}
public override string ToString()
{
return string.Join(".", bytes.Select(b => b.ToString()).ToArray());
}
}
這是一個工作演示:
class Program
{
static void Main(string[] args)
{
IPAddress ip = new IPAddress("192.168.1.2");
var obj = new SomeOuterObject() { stringValue = "Some String", ipValue = ip };
string json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
}
}
public class SomeOuterObject
{
public string stringValue { get; set; }
public IPAddress ipValue { get; set; }
}
輸出:
{"stringValue":"Some String","ipValue":"192.168.1.2"}
這篇關于Json.net 如何將對象序列化為值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!