使用環境VS2019
NuGet先加入Newtonsoft.json
並且使用以下宣告
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
在mamespace中 宣告json要使用的結構類別
public class cJsonDataItem
{
public string server { get; set; }
public string database { get; set; }
public string user { get; set; }
public string password { get; set; }
public string linkedserver { get; set; }
}
string temp = "{ "accountingAck": { "server": "127.0.0.1", "database": "Accounting_Ack_AZ", "user": "sa", "password": "123456789", "linkedserver": "REMOTE_LINK" }}";
var dynamic_obj =
JObject.Parse(temp);
string s = string.Empty;
StringBuilder strb = new StringBuilder();
StringBuilder strbb = new StringBuilder();
foreach (JProperty item in
dynamic_obj.Children())
{
strb.Append(item.Name);
strbb.Append(item.Value);
}
StringBuilder strbc = new StringBuilder();
StringBuilder strbd = new StringBuilder();
dynamic darray =
JsonConvert.DeserializeObject(strbb.ToString()); //此行為動態拿法 不用宣告最上面的類別
cJsonDataItem cjs =
JsonConvert.DeserializeObject<cJsonDataItem>(strbb.ToString()); //此行需要使用最上面的類別
最終透過cjs 可以輕鬆拿取到各項的字串結果
temp = cjs.server;
temp = cjs.database;