c#中jeson字符串和OBJECT对象的相互转换

对于本问题   我用三步来分别说明实现过程

1、定义一个类---- 实现转换的具体方法

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

namespace Test.JesonTest
{
    public static class JsonHelper
    {
        //定义json操作运算

        //将字jeson字符串转换为object对象
        public static T strToObject(string jsonString)
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
            }
        }

        //将object对象反序列为jeson字符串
        public static string objectToStr(object jsonObject)
        {
            using (var ms = new MemoryStream())
            {
                new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }
}

  

  说明:首先,当然是项目是3.5+的;必须添加引用:System.Runtime.Serialization 和 System.ServiceModel

2、创建一个OBJECT对象类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Test.JesonTest
{
    public class Person
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }

       public Person() {
           id = 0;
           name = "xuhyuan";
           age = 88;
        }
    }
}

 

  3、具体调用实现实例

      前台.aspx页面html。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Testjeson.aspx.cs" Inherits="Test.JesonTest.Testjeson" %>




    


    




      

  c#页面后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

namespace Test.JesonTest
{
    public partial class Testjeson : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        //将jeson字符串转换为object
        protected void but_str_obj_Click(object sender, EventArgs e)
        {
            string str_jeson = txt_resoult.Text.Trim();

            if (!string.IsNullOrEmpty(str_jeson))
            {
                List pes=new List();
                pes = JsonHelper.strToObject>(str_jeson);
               str_jeson="";
                for (int i = 0; i < pes.Count; i++)
                {
                    str_jeson += "id=" + pes[i].id + ";name=" + pes[i].name + ";age=" + pes[i].age + "


"; } } txt_resoult.Text+=str_jeson; } //将object转换为jeson字符串 protected void but_obj_str_Click(object sender, EventArgs e) { Person pe = new Person(); List pes = new List(); pes.Add(pe); pes.Add(pe); pes.Add(pe); //反序列化实现 string json = JsonHelper.objectToStr(pes); txt_resoult.Text = json; // 序列化----利用js实现 //JavaScriptSerializer jss = new JavaScriptSerializer(); } } }

 

你可能感兴趣的:(c#中jeson字符串和OBJECT对象的相互转换)