JSON to Class

  • 3782
  • 0

摘要:JSON to Class

C# 中要將物件轉 JSON字串或 JSON字串轉物件,請參考 http://james.newtonking.com/projects/json-net.aspx,該裝的裝完之後,寫法大概像這樣:

JsonConvert.SerializeObject(ObjectToSerialize);
JsonConvert.DeserializeObject 小於 objecttype 大於(JSONstring);//有沒有八字太輕沒事就撞到點部落補 html tag例外狀況的八卦

JavaScript中要將 JSON字串轉物件:

JSON.parse('{"a":123,"b":"ccc"}')

物件轉 JSON字串:

JSON.stringify({"a":123,"b":"ccc"})

注意物件屬性依標準要用雙引號包起來,不然就算現在能動,日後可能會錯的不明不白。

以上是囉嗦的補充;本文要記錄的是,從 WebService收到的 JSON string產生 class宣告…http://jsfiddle.net/grence/kBpRt/,

var o = {
    "Num": 8,
    "Name": "DDDDYYY",
    "day": 1266199200000,
    "qty": -999,
    "Limit": null
};

function writeline(output) {
    document.write(output + "
");
}

for (var p in o) {
    var out = "";
    switch (typeof o[p]) {
    case "string":
        out += "public string " + p;
        break;
    case "number":
        if (o[p] > 2147483647) out += "public long " + p;
        else if (o[p].toString(10).indexOf('.') != -1) out += "public float " + p;
        else out += "public int " + p;
        break;
    case "object":
        out += "public object " + p;
        break;
    default:
        out = "//" + p;
        break;
    }
    out += " { get; set; } ";
    writeline(out);
}

知道這在做什麼又剛好能拿去用的就請隨意啦 :p