[英]Newtonsoft.Json fail to converting from JSON to ICollection<Object>
[英]NewtonSoft - Converting JSON to an Object
我正在嘗試將 JSON 文件寫入對象。 這就是我創建 JSON 文件的方式。
var ActiveCustomer = new Customer(userID, fName, lName, pNumber, sLocation);
string json = JsonConvert.SerializeObject(ActiveCustomer, Newtonsoft.Json.Formatting.Indented);
using (StreamWriter file = File.CreateText(curFile))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, json);
}
Console.WriteLine(json);
我已經閱讀了文檔,這是我最接近從中創建對象的方法:
var ReadFromFile = JsonConvert.DeserializeObject<Customer>(File.ReadAllText(curFile));
Console.WriteLine(ReadFromFile);
它打印出字符串,然后包含一個長錯誤,說明它無法將字符串轉換為對象。
客戶類別::
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace Project0.Lib
{
public class Customer
{
public string _CustomerID { get; set; }
public string _FirstName { get; set; }
public string _LastName { get; set; }
public string _PhoneNumber { get; set; }
public string _StoreLocation { get; set; }
public Customer()
{
}
public Customer(string customerID, string firstName, string lastName, string phonenumber,string storelocation)
{
this._CustomerID = customerID;
this._FirstName = firstName;
this._LastName = lastName;
this._PhoneNumber = phonenumber;
this._StoreLocation = storelocation;
}
public override string ToString()
{
return _CustomerID + " " + _FirstName + " " + _LastName + " " + _PhoneNumber + " " + _StoreLocation;
}
}
}
在反序列化字符串的代碼周圍粘貼一個 try/catch,首先將字符串取出到一個變量中,然后在運行時,打破它並檢查字符串的“外觀”,確保 json 字符串是正確的,我以前有有一個問題,參數名稱在單個語音標記內,而不是雙”
我看到問題可能出現在您的代碼中的一個方面(它可能會弄亂字符串)是:
string json = JsonConvert.SerializeObject(ActiveCustomer, Newtonsoft.Json.Formatting.Indented);
using (StreamWriter file = File.CreateText(curFile))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, json);
}
在這里,您正在序列化一個對象(很好),但是然后您使用 jsonserializer 再次序列化它? 這意味着它將與 Customer 對象類不匹配。 取而代之的可能只是將 json 字符串寫入文件,因此:
string json = JsonConvert.SerializeObject(ActiveCustomer, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(file, json);
https://json.org/example.html可能會有所幫助。
如果這不起作用,您能否編輯您的帖子以包含 JSON 字符串?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.