如何将JSON文件转换为List < T>c#

vcudknz3  于 5个月前  发布在  C#
关注(0)|答案(2)|浏览(64)

我无法将包含多个Account类型对象的JSON文件序列化。下面是我如何构建data.json文件。我有一个帐户列表List<Account>,它像往常一样序列化。我通过添加新行来分隔json文件中的每个对象。

List<Account> listOfAccounts = new List<Account>();
if (listOfAccounts != null)
{
    foreach (var item in listOfAccounts)
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        string outputJSON = ser.Serialize(item);
        // I added Environment.NewLine to separate each account in json file.
        File.AppendAllText("data.json", outputJSON + Environment.NewLine);
    }
}

字符串
现在,当我试图从JSON文件中检索所有帐户到List<Account>时,我得到一个错误:System.ArgumentException: 'Invalid JSON primitive:
请帮助找到解决方案,这样我就可以从JSON文件中获取所有对象。

private void JsonFileLoad()
{
    if(File.Exists("data.json"))
    {
        String JSONtxt = File.ReadAllText("data.json");
        JavaScriptSerializer ser = new JavaScriptSerializer();
        // Not sure how to deserialize all lines into List<account>
        List<Account> desirializedAccounts = ser.Deserialize<List<Account>>(JSONtxt);                      
    }
}


我真的很感激你能提供的任何帮助。

dba5bblo

dba5bblo1#

首先,你应该以标准的json格式序列化。你所做的是序列化对象并写入文件。它应该是,将列表完全序列化为json格式。但假设你可能有特定的原因,我已经给出了许多可能的解决方案在不同的情况下。
注意:我使用Newtonsoft.json,因为它很快,我发现它很容易。http://www.newtonsoft.com/json
https://www.nuget.org/packages/newtonsoft.json/
解决方法:

//Class for testing object
public class Account
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

字符串

方案一:推荐

/// <summary>
/// Serializing the list in single go
/// </summary>
public void Serialize()
{
    List<Account> listOfAccounts = new List<Account>();
    listOfAccounts.Add(new Account { Id = 1, Name = "First" });
    listOfAccounts.Add(new Account { Id = 2, Name = "Second" });
    listOfAccounts.Add(new Account { Id = 3, Name = "Third" });

    string outputJSON = Newtonsoft.Json.JsonConvert.SerializeObject(listOfAccounts, Newtonsoft.Json.Formatting.Indented);
    File.WriteAllText(@"c:\temp\data.json", outputJSON + Environment.NewLine);
}

/// <summary>
/// Serializing the list, one by one object
/// Comma is appended to every object in json format
/// Finally, enclosed it with [ and ] to make it array of objects
/// </summary>
public void Serialize2()
{
    List<Account> listOfAccounts = new List<Account>();
    listOfAccounts.Add(new Account { Id = 1, Name = "First" });
    listOfAccounts.Add(new Account { Id = 2, Name = "Second" });
    listOfAccounts.Add(new Account { Id = 3, Name = "Third" });
    string outputJSON = "";
    foreach(var item in listOfAccounts)
    {
        outputJSON += Newtonsoft.Json.JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented)+",";
    }

    File.WriteAllText(@"c:\temp\data.json", "["+outputJSON + "]");
}

/// <summary>
/// Read serialized data into list of objects
/// </summary>
public void DeSerialize()
{
    if (File.Exists(@"c:\temp\data.json"))
    {
        String JSONtxt = File.ReadAllText(@"c:\temp\data.json");
        var accounts = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<Account>>(JSONtxt);
    }
}

方案二:根据您的要求

/// <summary>
/// Non standard json serialization (object one by one) Highly discouraged unless you have specific reason
/// Assuming the output will not have internal objects 
/// </summary>
public void SerializeNonStandard()
{
    List<Account> listOfAccounts = new List<Account>();
    listOfAccounts.Add(new Account { Id = 1, Name = "First" });
    listOfAccounts.Add(new Account { Id = 2, Name = "Second" });
    listOfAccounts.Add(new Account { Id = 3, Name = "Third" });

    foreach (var item in listOfAccounts)
    {
        string outputJSON = Newtonsoft.Json.JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented);
        File.AppendAllText(@"c:\temp\data-ns.json", outputJSON + Environment.NewLine);
    }
}
/// <summary>
/// Deserializes the list in one by one fashion and appends to list
/// </summary>
public void DeSerializeNonStandard()
{
    if (File.Exists(@"c:\temp\data-ns.json"))
    {
        List<Account> listOfAccounts = new List<Account>();
        String JSONtxt = File.ReadAllText(@"c:\temp\data-ns.json");

        //Capture JSON string for each object, including curly brackets 
        Regex regex = new Regex(@".*(?<=\{)[^}]*(?=\}).*", RegexOptions.IgnoreCase);
        MatchCollection matches = regex.Matches(JSONtxt);
        foreach(Match match in matches)
        {
            string objStr = match.ToString();
            Account account = Newtonsoft.Json.JsonConvert.DeserializeObject<Account>(objStr);
            listOfAccounts.Add(account);
        }
    }
}

/// <summary>
/// Deserializes the non standard json to list of accounts
/// Splits the object strings, merges with comma and encloses with [] to make it array of objects format and deserializes
/// </summary>
public void DeSerializeNonStandardList()
{
    if (File.Exists(@"c:\temp\data-ns.json"))
    {
        String JSONtxt = File.ReadAllText(@"c:\temp\data-ns.json");

        //Capture JSON string for each object, including curly brackets 
        Regex regex = new Regex(@".*(?<=\{)[^}]*(?=\}).*", RegexOptions.IgnoreCase);
        MatchCollection matches = regex.Matches(JSONtxt);

        string joinedJSON = string.Join(",", matches.Cast<Match>().Select(m => m.Value));
        joinedJSON = string.Format("[{0}]", joinedJSON);

        var listOfAccounts = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<Account>>(joinedJSON);

    }
}

icomxhvb

icomxhvb2#

您正在序列化Account而不是List of Account,这就是为什么序列化失败的原因。您需要在新行中分隔这些帐户吗?如果是这样,您可以尝试在data.json中的第一个和最后一个char ']'中添加char '['。

相关问题