c#对象和json字符串转换
using System;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
namespace WinFormsApp1
{
static class Program
{
static void Main()
{
Car c = new Car();
c.id = 345;
c.name = "baoma";
Person p = new Person();
p.id = 1;
p.name = "wang";
p.car = c;
string ps = ObjectToJSON(p);
System.Diagnostics.Trace.WriteLine(ps);
Person p2 = JsonToObject<Person>(ps);
System.Diagnostics.Trace.WriteLine(p2.name);
}
//json字符串转对象
public static T JsonToObject<T>(string jsonText)
{
DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
T obj = (T)s.ReadObject(ms);
ms.Dispose();
return obj;
}
//对象转json字符串
public static string ObjectToJSON<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
string result = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
ms.Position = 0;
using (StreamReader read = new StreamReader(ms))
{
result = read.ReadToEnd();
}
}
return result;
}
}
public class Person{
public int id;
public string name;
public int[] a = new int[10];
public Car car;
}
public class Car {
public int id;
public string name;
public Boolean[] b =new Boolean[10];
}
}