我想将以下类序列化/反序列化为JSON:
public class Employee
{
string name;
Position position;
}
public class Position
{
string positionName;
int salary;
}
棘手的部分是我想将Position
字段视为Employee
字段,因此JSON看起来像这样:
{
"name": "John",
"positionName": "Manager",
"salary" : 1000
}
如何使用Json.NET实现这一目标?
答案 0 :(得分:2)
您要么将其反序列化为匿名对象(推荐)实现此处所述的自定义反序列化:
Merge two objects during serialization using json.net?
如果还有其他问题,请告诉我们。
以下是一个示例(您可以在提供的链接中找到它):
public class FlattenJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
return;
}
JObject o = (JObject)t;
writer.WriteStartObject();
WriteJson(writer, o);
writer.WriteEndObject();
}
private void WriteJson(JsonWriter writer, JObject value)
{
foreach (var p in value.Properties())
{
if (p.Value is JObject)
WriteJson(writer, (JObject)p.Value);
else
p.WriteTo(writer);
}
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return true; // works for any type
}
}
答案 1 :(得分:2)
我的解决方案就是这个
static void Main(string[] args)
{
Position p = new Position();
p.positionName = "Manager";
p.salary = 1000;
Employee e = new Employee();
e.name = "John";
e.position = p;
ResultJson r = new ResultJson();
r.name = e.name;
r.positionName = e.position.positionName;
r.salary = e.position.salary;
var result = JsonConvert.SerializeObject(r);
Console.WriteLine(result);
Console.ReadLine();
}
}
public class Employee
{
public string name { get; set; }
public Position position { get; set; }
}
public class Position
{
public string positionName { get; set; }
public int salary { get; set; }
}
public class ResultJson
{
public string name { get; set; }
public string positionName { get; set; }
public int salary { get; set; }
}
使用单独的模型进行结果
答案 2 :(得分:-1)
您可以将此代码用于NewtonSoft.Json库
[JsonObject]
public class Employee
{
[JsonProperty("name")]
string name;
[JsonProperty("positionName")]
string positionName;
[JsonProperty("salary")]
int salary;
}
使用One class代替2,或实现自己的解析器
答案 3 :(得分:-2)
尝试这种方式。 { "姓名":" John", "位置&#34 ;: [{ " positionName":"经理", "工资" :1000 }] }