解析C#拼接Json串的⼏种⽅法
C#定义多⾏字符串的⽅式
在定义的前⾯加上@符号:
string aa = @"asdfsdfsd
fsdsfsdfsdfsdfsdfsdfs
safasfsadfsdfasfsfsdfsd ";
在C#中拼接字符串有⼏种⽅法
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
安卓在线解析jsonStringBuilder 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 + "}";
TODO:输出
{
"speed": 591,
"direction": 0
}
"{\"Bool_Type\":\"Bool\",\"Int_Type\":6666666,\"Float_Type\": 66.99,\"String_Type\":\"这是String类型
\",\"Vector2_Type\":{\"x\":666.0,\"y\":666.0},\"Vector3_Type\":{\"x\":666.0,\"y\":666.0,\"z\":666.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"); Jobject 数据结构的解析:
⾸先下载Newtonsoft.Json,增加引⽤using Newtonsoft.Json.Linq;
把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
}]
}
}
}
可放到json官⽹在线JSON校验格式化⼯具⾥解析。
代码如下:
1,新建类:
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; }
}
2,获取值:
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
到此这篇关于解析C#拼接Json串的⼏种⽅法的⽂章就介绍到这了,更多相关C#拼接Json串内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。