c# JSON将文件反序列化为对象列表失败,导致将字符串转换为集合错误



我有一个学校的小项目,我们在这里处理一些json的东西。我可以把对象列表写进JSON,这个文件是一个有效的JSON格式。不,一旦我加载相同的文件,我确实收到一个错误抱怨不能转换。信息如下:

Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Error converting value "[
{
"ID": 500455154,
"Title": "GameOne",
"MinAge": 14,
"Price": 12.8,
"State": "New",
"Players": 4
},
{
"ID": 860100321,
"Title": "Gametwo",
"MinAge": 14,
"Price": 12.8,
"State": "New",
"Players": 4
},
{
"ID": 358239485,
"Title": "Gamethree",
"MinAge": 14,
"Price": 12.8,
"State": "New",
"Players": 4
}
]" to type 'System.Collections.Generic.List`1[Ludothek.Game]'. Path '', line 1, position 513.
Source=Newtonsoft.Json
StackTrace:
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Ludothek.DATA.loadData_Games() in eposLudothekLudothekDATA.cs:line 71
at Ludothek.Program.Main(String[] args) in rProgram.cs:line 16
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.List`1[Ludothek.Game].

这是我加载该文件并将其推入现有游戏列表的函数:

public List<Game> loadData_Games()
{
var Gl = new List<Game>();
string[] files = Directory.GetFiles(folder, "games.json");
foreach (var file in files)
using (StreamReader sr = new StreamReader(file))
{
using (JsonReader jsr = new JsonTextReader(sr)) {
var Serializer = new JsonSerializer();
Gl = (List<Game>)Serializer.Deserialize(jsr, typeof(List<Game>));
// above is where it hits the fan...
}

}

return Gl;
}

当然这里是游戏类:

public class Game : AbstGame
{
[JsonProperty("ID")]
public override int ID { get ; }
[JsonProperty("Title")]
public override string Title { get ; set ; }
[JsonProperty("MinAge")]
public override int MinAge { get ; set ; }
[JsonProperty("Price")]
public override double Price { get; set ; }
[JsonProperty("State")]
public override string State { get; set ; }
[JsonProperty("Players")]
public int Players { get; set; }

public Game(string title, int minAge, double price,string state, int players)
{
Random rnd = new Random();
ID = rnd.Next(1, 999999999);
Title = title;
MinAge = minAge;
Price = price;
State = state;
Players = players;
}

我是这样写的:

public void backUp_Games(List<Game> games)
{
string filename = "games";
string jsonGames = JsonConvert.SerializeObject(games,Formatting.Indented);
backUp(filename, jsonGames);

}
public void backUp(string fileName ,string json)
{
string filename = @"C:.....DesktopJsonTest"+fileName+".json"; // not the actual path ;)
File.WriteAllText(filename, JsonConvert.SerializeObject(json,Formatting.Indented));
}

我真的在网上寻找解决这个问题的方法,并尝试了其他几种方法。我看不出问题所在。还有谁看到了,能给我点提示吗?

我在代码中所做的就像生成具有某些属性的游戏列表。一旦窗口关闭,我将把游戏对象列表推入json并保护它,一旦我们打开它,它就会重新加载。所以它需要从json中获取对象列表。

提前感谢!

这个文件是一个有效的JSON格式

是的,它是有效的JSON,但不是你所期望的。你只写了一个JSON字符串的文件。

简化的例子:

"foo"

这是有效的json。它只是一个字符串。您执行相同的操作,但字符串内容看起来像JSON。

"{"foo": "bar"}"

这仍然只是一个字符串,没有JSON对象。

这就是为什么你会得到错误:Could not cast or convert from System。String to System.Collections.Generic.List ' 1[Ludothek.Game].

这是你要做的…

string jsonGames = JsonConvert.SerializeObject(games,Formatting.Indented);
// string jsonGames is the JSON you want but then you do...
File.WriteAllText(filename, JsonConvert.SerializeObject(json,Formatting.Indented));

所以,你做了两次JSON编码,JSON编码一个JSON字符串将得到一个如上所述的字符串。

解决方案:只编码一次。

最新更新