日期:2014-05-18  浏览次数:20553 次

操作JSON格式数据
JSON在AJAX架构得到广泛应用,是一种有应用前途的数据格式。 

问题两个:

(1)在前台应用JSON数据非常方便,但是在后台,比如如下JSON数据
[{"ID":"3","Order":"9"},{"ID":"1",Order":"6"},{"ID":"2",Order":"8"}]
希望在后台基于ID的大小进行排序,得到如下JSON数据
[{"ID":"1","Order":"6"},{"ID":"2",Order":"8"},{"ID":"3",Order":"9"}]
有没有高效的实现代码或方法

(2)希望大家能给出后台操作其他JSON格式数据的代码,越多越好了,大家多交流;

愿大家上网开心,工作顺利。。。



------解决方案--------------------
定义实体类
static T Deserialize <T>(string json) 

T obj = Activator.CreateInstance <T>(); 
using (MemoryStream ms = 
new MemoryStream(Encoding.UTF8.GetBytes(json))) 

System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = 
new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); 
return (T)serializer.ReadObject(ms); 


再排序
------解决方案--------------------
C# code

//
引用
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

------解决方案--------------------
C# code

//最后改了下

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

namespace ConsoleApplication1
{
    [DataContract]
    public sealed class FooDef
    {
        [DataMember(Name = "ID", IsRequired = true)]
        public string ID { get; set; }

        [DataMember(Name = "Order", IsRequired = true)]
        public string Order { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string bar = "[{\"ID\":\"3\",\"Order\":\"9\"},{\"ID\":\"1\",\"Order\":\"6\"},{\"ID\":\"2\",\"Order\":\"8\"}]";
            List<FooDef> newEntities = Deserialize<FooDef>(bar);
            var s = from l in newEntities orderby l.ID select l;
        }
        static List<T> Deserialize<T>(string str)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<T>));
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(str)))
            {
                List<T> entities = (List<T>)json.ReadObject(stream);
                stream.Close();
                return entities;
            }
        }
    }
}