Reputation:
I'm not allowed to import new packages at the customer. I'm only allowed in the area between obtaining a String
object looking like a JSON string and a return, where I'm supposed to return some parts of it in a List<String>
.
I feel terribly limited and as far I can see, I can't proceed. My best bet is using Regex
object but perhaps there's a smoother solution? (I believe I'm allowed to use XDocument too, and LINQ, if that's of any help).
Suggestions?
Upvotes: 1
Views: 2853
Reputation: 1613
Follow this manual and you should be able to do it.
You only need to import System.Runtime.Serialization.dll (standerd .net dll)
edit:
You have this method
public static T JsonDeserialize<T> (string jsonString)
If you know what json you will get you can create object like this:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
So you can use it like this:
string jsonString = "{\"Age\":28,\"Name\":\"Tom\"}";
Person p = JsonHelper.JsonDeserialize<person>(jsonString);
edit2:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main(string[] args)
{
string json = "[{\"Age\":28,\"Name\":\"Tom\"},{\"Age\":18,\"Name\":\"Andes\"},{\"Age\":32,\"Name\":\"Lily\"}]";
List<Person> persons = new List<Person>(JsonHelper.JsonDeserialize<Person[]>(json));
}
Edit 3: JsonHelper is a class implemting a default settup.
/// <summary>
/// JSON Serialization and Deserialization Assistant Class
/// </summary>
public class JsonHelper
{
/// <summary>
/// JSON Serialization
/// </summary>
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
/// <summary>
/// JSON Deserialization
/// </summary>
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
}
Upvotes: 1