【发布时间】:2017-12-13 21:28:03
【问题描述】:
使用以下示例序列化了一个类
using Newtonsoft.Json;
using System;
namespace ConsoleAppCompare
{
class Program
{
static void Main(string[] args)
{
Movie movie = new Movie()
{
Name = "Avengers",
Language = "En",
Actors = new Character[] { new Character(){Name="Phil Coulson"},new Character(){Name="Tony Stark"}
}};
Console.WriteLine(JsonConvert.SerializeObject(movie, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }));
Console.ReadLine();
}
}
class Movie
{
public string Name { get; set; }
public string Language { get; set; }
public Character[] Actors { get; set; }
}
class Character
{
public string Name { get; set; }
}
}
以上示例生成以下 json
{
"$type": "ConsoleAppCompare.Movie, ConsoleAppCompare",
"Name": "Avengers",
"Language": "En",
"Actors": {
"$type": "ConsoleAppCompare.Character[], ConsoleAppCompare",
"$values": [
{
"$type": "ConsoleAppCompare.Character, ConsoleAppCompare",
"Name": "Phil Coulson"
},
{
"$type": "ConsoleAppCompare.Character, ConsoleAppCompare",
"Name": "Tony Stark"
}
]
}
}
现在,在另一个程序 上,它无法访问上述模型,
我必须将字符串反序列化为一个对象,但我尝试过的任何方法似乎都不起作用......
为了创建我的新模型,我复制了剪贴板上的 json 并使用了 Visual Studio 的“选择性粘贴”功能
using Newtonsoft.Json;
using System;
using System.IO;
namespace ConsoleAppCompare
{
class Program
{
static void Main(string[] args)
{
var s = File.ReadAllText(@"C:\Users\nvovo\Desktop\asdf\aa.txt");
Rootobject movie = null;
// nothing Works :(
//movie =JsonConvert.DeserializeObject<Rootobject>(s, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
//movie = JsonConvert.DeserializeObject<Rootobject>(s, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None });
//movie = JsonConvert.DeserializeObject<Rootobject>(s);
Console.ReadLine();
}
}
public class Rootobject
{
public string type { get; set; }
public string Name { get; set; }
public string Language { get; set; }
public Actors Actors { get; set; }
}
public class Actors
{
public string type { get; set; }
public Values[] values { get; set; }
}
public class Values
{
public string type { get; set; }
public string Name { get; set; }
}
}
我可以对此做些什么吗?或者我应该尝试找到原始课程?
更新
我不关心“$type”属性。它甚至不在原始模型上。我只想将 JSON 反序列化为强类型模型,包括集合(我的真实类有更多嵌套级别),但自动生成的类型(使用 Paste Json)不起作用。
【问题讨论】: