C#拼接Json串的幾種方法

每天进步多一点發表於2024-07-16

1. 利用 JsonConvert.SerializeObject方法 (Nuget獲取Newtonsoft.Json Package),需要Newtonsoft.Json 支援。

string uid = "22";
 
var abcObject = new
{
  AccessKey = 11,
  CustomerNo = uid,
  mc = "33",
  qd = "44",
  mr = "55",
  insertDate = DateTime.Now
};
string serJson = JsonConvert.SerializeObject(abcObject);

2. 利用StringBuilder

StringBuilder str = new StringBuilder();
str.Append("{");
str.Append("AccessKey:\"" + 11 + "\",");
str.Append("mc:\"" + 22 + "\",");
str.Append("qd:\"" + 33 + "\"");
str.Append("}");
string serJson = str.ToString();

3. 直接拼接字串

string json = "{\"speed\":" + speed + "," + "\"direction\":" + direction + "}";
 
//輸出
{
    "speed": 591,
    "direction": 0
}

4. 利用StringFormat

string mc = "22";
string id = "11";
string serJson = string.Format("[{{ AccessKey:\"{0}\",mc:\"{1}\"}},{{ AccessKey:\"{2}\",mc:\"{3}\"}}]", id, mc, "33", "44");

5. Jobject 資料結構的解析

//Jobject的內容格式如下:
{
 "code": 200,
 "msg": "SUCCESS",
 "data": 
{
"id": "12345678", "name": "張三", "sex": "", "result":
{
"access_token": "49d58eacd7811e463429a1ae10b42173", "user_info":
[{
"school": "社會大學", "major": "軟體開發", "education": "本科", "score": 97 },
{
"school": "湖南大學", "major": "軟體工程", "education": "研究生", "score": 100 }] } } }

新建類:

public class UserInfo
{
      public string id { get; set; }
      public string name { get; set; }
      public string sex { get; set; }
      public string access_token { get; set; }
      public string school { get; set; }
      public string major { get; set; }
      public string education { get; set; }
      public string score { get; set; }
}

獲取值:

JObject result = new JObject();//假設result為資料結構
UserInfo userinfo = new UserInfo();
userinfo.id = result["data"].Value<string>("id");//id
userinfo.name = result["data"].Value<string>("name"); //name
userinfo.sex = result["data"].Value<string>("sex"); //sex
userinfo.access_token= result["data"]["result"]["access_token"].ToString();//access_token
JArray res = result["data"]["result"].Value<JArray>("user_info");
JObject obj = JObject.Parse(res[0].ToString());//只獲取資料結構中第一個userinfo裡的資料資訊
userinfo.school = obj.Value<string>("school"); //schoool
userinfo.major = obj.Value<string>("major");//major
userinfo.education = obj.Value<string>("education");//education
userinfo.score= obj.Value<string>("score");//score

相關文章