fastJson Deserialize Unhandled Exception

2.9k views Asked by At

I'm using fastJson library to deserialize a json string to a "Person" object. The Person class is defined below:

class Person
{
    public string type;
    public string id;
    public string name;
}

The Json string is:

[{
"type": "/basketball/basketball_player", 
"id": "/en/rasheed_wallace", 
"name": "Rasheed Wallace"
},
{
"type": "/basketball/basketball_player", 
"id": "/en/tayshaun_prince", 
"name": "Tayshaun Prince"
}]

When I use the code:

var obj = fastJSON.JSON.Instance.ToObject<List<Person>>(str);

It shows an unhandled exception that

Failed to fast create instance for type
'System.Collections.Generic.List`1[[JsonSample.Person, JsonSample, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null]]' from assemebly  
System.Collections.Generic.List`1[[JsonSample.Person, JsonSample, Version=1.0.0.0, 
Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, 
PublicKeyToken=b77a5c561934e089'

But everything works fine in Newtonsoft.Json library if I use the code:

var obj = JsonConvert.DeserializeObject<List<Person>>(str);

So is this a bug of fastJson or am I not using fastJson in a correct way?

1

There are 1 answers

2
Mike Two On BEST ANSWER

It is because Person is not public. Change your class definition to

public class Person
{
    public string type;
    public string id;
    public string name;
}

I tried running your code as is and got the same exception. I modified Person to be public and the exception went away.