Ronald
Ronald

Reputation: 1113

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);

Upvotes: 2

Views: 9639

Answers (2)

roqz
roqz

Reputation: 1018

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);
    }

Upvotes: 3

dcastro
dcastro

Reputation: 68710

That's not a valid json string, try:

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

Upvotes: 1

Related Questions