rohit singh
rohit singh

Reputation: 1289

Getting error using JsonConvert.DeserializeObject when converting JSON to string c#

When converting JSON to string (2nd method), I'm getting the error:

Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: [. Path '', line 1, position 1.'

Why I'm getting an error in the 2nd method but the code is working fine in the 1st method, is there any solution for the 2nd method as I have to work with that method only?

Code:

static void Main(string[] args)
{
   string abc = "[{\"provider\":\"test\",\"schemes\":[{\"tyo\":\"1\",\"check\":\"99\",\"slotNumber\":\"0\"},{\"tyo\":\"2\",\"check\":\"99\",\"slotNumber\":\"469\"}]}]";

   var value = abc.FromJson().ToString();

   // Getting error in below line
   var value2 = abc.FromJson(typeof(String));       
}     

// First Method                    
public static object FromJson(this string json)
{
   var value = JsonConvert.DeserializeObject(json);
   return value;
}

// Second Method
public static object FromJson(this string json, Type type)
{
   var value = JsonConvert.DeserializeObject(json, type);     
   return value;
}                    

Upvotes: 0

Views: 4078

Answers (1)

Vivien Sonntag
Vivien Sonntag

Reputation: 4629

JsonConvert.DeserializeObject(string, Type) tries to parse JSON to the given type, assigning the properties of your object to properties of the resulting type. As String does not provide the necessary properties (In your case it probably needs to be an array with objects that provide properties like provider and schemes) it cannot be deserialized to a string.

This works as the deserialization to an array of objects is supported by Newtonsoft.Json :

var value2 = abc.FromJson(typeof(object[]));

Upvotes: 4

Related Questions