unity使用Netjson自定义向量Vector解析
程序员文章站
2022-04-02 18:51:14
...
Newtonsoft.Json.dll
以Vector2为例:
解析Vector2你可能会解析出:“x”:0,“y”:1之类不符合你预期的字符串。
自定义解析出来的规则(例:你希望解析规则是"(0,1)".而不需要X,Y或其他乱七八糟的元素)
1.定义一个类,重写:
public class Vector2Converter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Vector2));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
string[] v2Str = reader.Value.ToString().Split(',');
v2Str[0] = v2Str[0].Replace("(", "");
v2Str[1] = v2Str[1].Replace(")", "");
return new Vector2(float.Parse(v2Str[0]), float.Parse(v2Str[1]));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Vector2 v2 = (Vector2)value;
serializer.Serialize(writer, "(" + v2.x + "," + v2.y + ")");
}
}
2.转换:
//Json转类
string json;
JsonConvert.DeserializeObject<T>(json, new Vector2Converter());
//类转Json
T t;
JsonConvert.SerializeObject(t, new Vector2Converter());