如何在C#中使用Json.Net从文件中读取Json集合

时间:2014-08-12 09:36:01

标签: c# json json.net

我有这个json文件:

{
   “transactions”:[
      {
         “type”:”deposit”,
         “account_id”:123456789012345,
         “amount”:20000.0
      },
      {
         “type”:”deposit”,
         “account_id”:555456789012345,
         “amount”:20000.0
      },
      {
         “type”:”payment”,
         “account_id”:123456789012345,
         “amount”:20000.0
      },
      {
         “type”:”transfer”,
         “from”:555456789012345,
         “to”:123456789012345,
         “amount”:20000.0
      }
   ]
}

我想用JSON.net读取这个文件。

我尝试了这段代码,但它有一些unhandeld错误:

var records = JsonConvert.DeserializeObject<List<Type>>(File.ReadAllText(FileAddress));
using (StreamReader SrFile = File.OpenText(FileAddress))
{
    JsonSerializer Serializer = new JsonSerializer();
    JsonAccount newJsonAccount = (JsonAccount)Serializer.Deserialize(SrFile, typeof(JsonAccount));
}

错误是:

  

Newtonsoft.Json.dll中发生未处理的“Newtonsoft.Json.JsonReaderException”类型异常

     

其他信息:解析时遇到意外的字符   价值: 。路径'',第0行,第0位

现在它有这个错误:

其他信息:将值“transactions”转换为“ImportAndExport.MainForm + JsonAccount”时出错。路径'',第1行,第14位。

更新2:

现在错误是:

    An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll

Additional information: Invalid character after parsing property name. Expected ':' but got: t. Path '', line 2, position 7.

1 个答案:

答案 0 :(得分:2)

您的错误:

Additional information: Unexpected character encountered while parsing value: �. Path '', line 0, position 0.

可能是由于您使用卷曲引号而不是直引号引起的。用标准的直引号替换它。

编辑:

如果您遇到更多JSON解析问题,我将解析该JSON:

         string jsonString = @"{
    ""transactions"": [
        {
            ""type"": ""deposit"",
            ""account_id"": 123456789012345,
            ""amount"": 20000
        },
        {
            ""type"": ""deposit"",
            ""account_id"": 555456789012345,
            ""amount"": 20000
        },
        {
            ""type"": ""payment"",
            ""account_id"": 123456789012345,
            ""amount"": 20000
        },
        {
            ""type"": ""transfer"",
            ""from"": 555456789012345,
            ""to"": 123456789012345,
            ""amount"": 20000
        }
    ]
}";

        var recordObject = JObject.Parse(jsonString);

如果我想获得最后一笔交易

        var lastRecord = JObject.Parse(jsonString)["transactions"].Last()

如果我想要存款记录

        var deposits = from transactions in JObject.Parse(jsonString)["transactions"]
                       where transactions["type"].ToString().Equals("deposit")
                       select transactions;