Here is my very simple C# class object that I am trying to turn into a JSON string and stringifying:
public class rTestObject
{
public rTestObject()
{
Name = "Hello";
State = 7;
}
public string Name { get; set; }
public int State { get; set; }
}
I call the following static method:
// Json.net
// from Newtonsoft.Json.dll
// version 8.0.2.19309
//
using Newtonsoft.Json;
public static string ConvertToJSON<T>(T obj)
{
return JsonConvert.SerializeObject(obj);
}
Which produces the following (expected) output:
{"Name":"Hello","State":7}
I call the following static method to stringify my JSON string
public static string Stringify(string json)
{
return JsonConvert.ToString(json);
}
Which produces the following (I think this is expected ??) output:
"{\"Name\":\"Hello\",\"State\":7}"
My question how do I get from:
"{\"Name\":\"Hello\",\"State\":7}"
back to rTestObject?
Here is what I have tried:
TRY 1
public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
{
Newtonsoft.Json.Linq.JObject j = Newtonsoft.Json.Linq.JObject.Parse(stringifiedJSON);
return ConvertFromJSON<T>(j.ToString());
}
Here is the exception:
{"Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 34."}
TRY 2
public static T ConvertFromJSON<T>(string jsonNotation)
{
return JsonConvert.DeserializeObject<T>(jsonNotation, NoNullStrings);
}
Here is the exception:
{"Error converting value \"{\"Name\":\"Hello\",\"State\":7}\" to type 'RestApi.Objects.rTestObject'. Path '', line 1, position 34."}
Solution:
Thank you Alexander I. !
public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
{
var json = JsonConvert.DeserializeObject<string>(stringifiedJSON);
return ConvertFromJSON<T>(json);
}