A class was serialized using the following sample
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; }
}
}
The above sample produces the following 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"
}
]
}
}
Now,on another program ,that doesn't have access to the above models,
I have to deserialize the string to an object but nothing I've tried seems to be working...
To create my new models I copied the json on my clipboard and used Visual Studio's "Paste Special" functionality
using Newtonsoft.Json;
using System;
using System.IO;
namespace ConsoleAppCompare
{
class Program
{
static void Main(string[] args)
{
var s = File.ReadAllText(@"C:Users
vovoDesktopasdfaa.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; }
}
}
Can I do anything about this or I should try to find the original classes?
Update
I don't care about the "$type" property. It's not even on the original models. I just want to deserialize the JSON to a strongly typed model, including the collections (my real classes have more nested levels) but the auto generated types (using Paste Json) don't work.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…