Neo
Neo

Reputation: 16219

Unable to Deserialize Object using Newton Json

I tried with following code but getting error for input parameter as string.

protected override object DeserializeCore(Type type, byte[] value)
{
     using (var ms = new MemoryStream(value))
     using (var sr = new StreamReader(ms, Encoding.UTF8))
     {
          var result = Newtonsoft.Json.JsonConvert.DeserializeObject(sr, type);
          return result;
     }
}

and I passed it as sr.ToString() getting error :

Unexpected character encountered while parsing value: S. Path '', line 0, position 0.

Upvotes: 0

Views: 1749

Answers (2)

Rick
Rick

Reputation: 841

Would this not be simpler?

    protected override object DeserializeCore(Type type, byte[] value) {
        var str = System.Text.Encoding.UTF8.GetString(value);
        return JsonConvert.DeserializeObject(str, type);
    }

(I can't figure out why you are using the streams. Is it related to some issue with the encoding?)

Upvotes: 1

Amit Kumar Ghosh
Amit Kumar Ghosh

Reputation: 3726

try this -

public class JsonObject
{
    public object Value { get; set; }
    public string Type { get; set; }
}

var s = "{'Value':{'something':'test'},'Type':'JsonData'}";
var o = DeserializeCore(typeof(JsonObject), Encoding.UTF8.GetBytes(s.ToCharArray()));

should work fine.

Upvotes: 1

Related Questions