简体   繁体   中英

Newtonsoft.Json.JsonSerializationException was unhandled by user code

What am I missing here? Why do I get this exception? Newtonsoft.Json.JsonSerializationException was unhandled by user code, Error converting value "[{"username":"someone","computername":"computer1","PID":"1234"}]" to type 'System.Collections.Generic.List`1[WebApplication4.PInfo]'. Path '', line 1, position 95.

The code is below, very simple class, very simple content, but a nasty error =(

public class PInfo
{
    public string username { get; set; }
    public string computername { get; set; }
    public string PID { get; set; }
}

string s = "\"[{\\\"username\\\":\\\"someone\\\",\\\"computername\\\":\\\"computer1\\\",\\\"PID\\\":\\\"1234\\\"}]\"";
var z = JsonConvert.DeserializeObject<List<PInfo>>(s);

I think you have an error in your Json string, the backslashes are maybe incorrect.

If you try this Json string

[{"username":"test","computername":"test","PID":"test"}]

that you can produce by yourself with the following program then everything works fine:

private static void test()
    {
        PInfo p = new PInfo();
        p.username = "test";
        p.computername = "test";
        p.PID = "test";
        List<PInfo> testlist = new List<PInfo>();
        testlist.Add(p);
        string json = JsonConvert.SerializeObject(testlist);

        var z = JsonConvert.DeserializeObject<List<PInfo>>(json);
    }

这不是有效的json字符串,请尝试:

string s = "[{\"username\":\"someone\",\"computername\":\"computer1\",\"PID\":\"1234\"}]";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM