Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''

Alex picture Alex · Mar 30, 2015 · Viewed 12.2k times · Source

I've been searching for the past 4 hours for ways on how to tackle this problem, and I've not yet found a solution.

I'm building an API with .NET and wish to parse JSON information that is sent back from API calls.

My current approach does the following:

private void PostNewPlayer(HttpContext context)
{
    // Create the serializer
    context.Request.InputStream.Position = 0;

    DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(ASPlayer));
    ASPlayer p = (ASPlayer)json.ReadObject(context.Request.InputStream);  <-- Exception here
    Int32 playerId = ASPlayerManager.InsertNewPlayer(p);
}

But I currently get an Exception at the indicated line. I have made sure my class implements the correct serialization namespaces:

using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Json;

The class I am trying to serialize has had its DataContract and Member fields set accordingly:

[DataContract]
public class ASPlayer
{
    [DataMember]
    private string _name;
    public string player_name 
    {
        get { return _name; }
        set { _name = value; }
    }

    [DataMember]
    private string _location;
    public string player_location
    {
       get { return _location; }
       set { _location = value; }
    }

    // Other vars
    ... 

    public ASPlayer(string name, string location)
    {
        _name = name;
        _location = location;
     }
}

However, when I use a HTTP client such as Postman to make a request I get the error stated in the question title

enter image description here

Answer

thumbmunkeys picture thumbmunkeys · Mar 30, 2015

I think you marked the wrong variables, this:

[DataMember]
private string _name;
public string player_name 

should be this:

private string _name;
[DataMember]
public string player_name