程 序 人 生

[每个人都是工程师,书写着属于自己的人生代码!--林海]
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#后台操作JSON数据

Posted on 2015-03-02 13:38  林海  阅读(14920)  评论(0编辑  收藏  举报
string ss = "";
string str = "{ID:'1',Name:'aaa',Details:[{ID:'111',Value:'1111111'}]}";
var obj11 = JsonConvert.DeserializeAnonymousType(str, new { ID = 0, Name = string.Empty, Details = new JArray() });
str = "[{ID:'1',Name:'aaa'},{ID:'2',Name:'bbb'}]";
str = "[{ID:'1',Name:'aaa',Details:[{ID:'111',Value:'1111111'}]},{ID:'2',Name:'bbb',Details:[{ID:'222',Value:'22222222'}]}]";
dynamic tok = JsonConvert.DeserializeObject(str);
foreach (JObject item in tok)
{
    var id = item["ID"].Value();
    var name = item["Name"].Value();
    //foreach (var item2 in item.Properties())
    //{
    //    var name = item2.Name;
    //    var v = item2.Value.ToString();
    //}
}

JArray jAry = (JArray)JsonConvert.DeserializeObject(str);
var ddd = jAry.ToString();
for (int i = 0; i < jAry.Count; i++)
{
    JObject obj = (JObject)jAry[i];
    ss += "ID:" + obj["ID"].ToString() + "\r\n";
    ss += "Name:" + obj["Name"].ToString() + "\r\n";
    JArray json = (JArray)obj["Details"];
    ss += "Detail:\r\n--------\r\n";
    for (int j = 0; j < json.Count; j++)
    {
        JObject jsonobj = (JObject)json[j];
        ss += "ID:" + jsonobj["ID"].ToString() + "\r\n";
        ss += "Value:" + jsonobj["Value"].ToString() + "\r\n";
        //var age = jsonobj["Value"].Value();
    }
    ss += "--------\r\n\r\n";
}

dynamic tok2 = JsonConvert.DeserializeObject(str);
if (tok is JArray)
{
    foreach (JObject item in tok2)
    {
        foreach (JProperty item2 in item.Properties())
        {

        }
    }
}



//Json字符串
string jsonStr = @"{ID:'1',Name:'aaa',Details:[{ID:'111',Value:'1111111'}]";
//匿名类
var objj = JsonConvert.DeserializeAnonymousType(jsonStr, new { ID = 0, Name = string.Empty, Details = new JArray() });
ss += "\r\n" + objj.Name + "\t" + objj.ID + "\t" + objj.Name;

var r1 = db.Box.Select(c => new { c.BoxID, c.Name }).ToList();



IEnumerable r2__ = db.Box.Select(c => new { c.BoxID, c.Name })
                                .AsEnumerable()
                                .Select(en => new JProperty(en.BoxID, en.Name));

//var relations = db.RelPaperAndProcesses.GroupBy(x => x.PaperGroupID).ToDictionary(x => x.Key, x => x.ToList().ConvertAll(y => new { ID = y.ID }));

//var r2 = db.Box.Select(c => new Tuple<string, string>(c.BoxID, c.Name)).ToList();

//        JObject sssj = new JObject( //创建JSON对象
//    db.Categories.Select(
//        c =>
//        new JProperty( //创建JSON属性
//            c.CategoryName, //属性名称(在这里是产品类别名称)
//            new JArray( //属性的值(在这里是该类别下的所有产品名称)
//                c.Products.Select(
//                    p =>
//                    p.ProductName
//                )
//            )
//        )
//    )
//);