2015年7月15日水曜日

object-Json相互変換


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;

namespace ConsoleApplication12
{
 class Program
 {
  static void Main(string[] args)
  {
   var model1 = new testData() { X = 123, Y = 345, P = new test2Data() { Z = 999 } };
   var json = JsonHelper.ToJson(model1);
   var model2 = JsonHelper.ToObject(json);
  }

 }

 public static class JsonHelper
 {
  public static T ToObject(string jsonString)
  {
   var jsonBytes = Encoding.Unicode.GetBytes(jsonString);
   using (var sr = new MemoryStream(jsonBytes))
   {
    var serializer = new DataContractJsonSerializer(typeof(T));
    return (T)serializer.ReadObject(sr);
   }
  }

  public static string ToJson(object obj)
  {
   using (var ms = new MemoryStream())
   {
    var s = new DataContractJsonSerializer(obj.GetType());
    s.WriteObject(ms, obj);
    return Encoding.UTF8.GetString(ms.ToArray());
   }
  }
 }

 [DataContract]
 public class testData
 {
  [DataMember]
  public int X { get; set; }
  [DataMember]
  public int Y { get; set; }
  [DataMember]
  public test2Data P { get; set; }
 }

 [DataContract]
 public class test2Data
 {
  [DataMember]
  public int Z { get; set; }
 }
}

0 件のコメント:

Androider