[C#] 一個有關於自定字串找尋JSON 格式的值 by JSON.net

2012-10-05


最近公司專案很多,需求也都很詭異..
所以需要這樣的東西,紀錄一下,有需要的人就拿去用吧…

只是寫得不好的部分,也請多多指教…
看一下JSON 資料..

{"Son":{"Son":null,"Name":"D-Son","Friends":null},"Name":"D1","Friends":[{"Son":null,"Name":"D1-1","Friends":[{"Son":null,"Name":"D1-1-1","Friends":null}]},{"Son":null,"Name":"D1-2","Friends":null}]}

有點亂我排一下版..

{"Name":"D1",
 "Son":{"Son":null,"Name":"D-Son","Friends":null},
 "Friends":
        [
          {
            "Name":"D1-1",
            "Son":null,
            "Friends":
                        [
                            {
                                "Name":"D1-1-1",
                                "Son":null,                
                                "Friends":null
                            }
                         ]
           },{
            "Name":"D1-2",
            "Son":null,
            "Friends":null}]
}

簡單的說 物件結構

D1 的 Son 是 D-Son

D1 的朋友 有 D1-1 , D1-2

D1-1 的朋友 有 D1-1-1

專案的需求就是 如果 我要 取得 D1-1-1 是否我可以直接這樣下指令 

"Friends[0].Friends[0].Name"

/// <summary>
///  透過自訂字串去搜尋JSON 語法
/// </summary>
/// <param name="expressionString">自訂字串</param>
/// <param name="jsonString">JSON format string</param>
/// <returns></returns>
public string GetJsonValueByCustomExpression(string expressionString, string jsonString)
{
    var res = jsonString;
    foreach (var p in expressionString.Split('.'))
    {
        //因為意外可能太多、所以直接回傳null 
        try
        {
            if (p.Contains("[") && p.Contains("]"))
            {
                var startIndex = p.IndexOf('[') + 1;
                var endIndex = p.IndexOf(']') - p.IndexOf('[') - 1;
                int num = int.Parse(p.Substring(startIndex, endIndex));
                var q = p.Substring(0, p.IndexOf('['));
                JObject tmp = JObject.Parse(res);
                res = tmp[q][num].ToString();
            }
            else
            {
                JObject tmp = JObject.Parse(res);
                res = tmp[p].ToString();
            }
        }
        catch
        {
            return "";
        }
    }
    return res;

}


這時候看一下我呼叫結果..


string pattern = "Name";
Response.Write(GetJsonValueByCustomExpression(pattern, jsonStr)+"<br />");
//D1


pattern = "Son.Name";
Response.Write(GetJsonValueByCustomExpression(pattern, jsonStr) + "<br />");
//D-Son


pattern = "Friends[0].Friends[0].Name";
Response.Write(GetJsonValueByCustomExpression(pattern, jsonStr) + "<br />");
//D1-1-1


pattern = "Friends[1].Name";
Response.Write(GetJsonValueByCustomExpression(pattern, jsonStr) + "<br />");
//D1-2



奇怪的需求 不過打完收工…
對了專案需要用到JSON.net 需引入..


當麻許的超技八 2014 | Donma Hsu Design.