0

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;
}                    
9
  • Click here! Check that i guess it's your problem. Commented Jan 3, 2019 at 12:25
  • 2
    I don't understand why you're trying to deserialize Json to a string as it's already a string! What are you trying to do? Commented Jan 3, 2019 at 12:30
  • 1
    Your question is misleading. You claim that you're getting an error in "the 2nd method", but your comments label it as "1st method". Are you just confused by your own comments in your debugging? Commented Jan 3, 2019 at 12:33
  • The example is just a sample console application. What I'm doing is i'm trying to convert the sample json abc to string by using the 2nd method which throws me error because my string contains backslash. Commented Jan 3, 2019 at 12:34
  • 1
    Your extension methods are pretty pointless. All they're really doing is making your code harder to read Commented Jan 3, 2019 at 12:34

1 Answer 1

4

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[]));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.