json字符串获取值
using Newtonsoft.Json.Linq;
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string mStr = "{\"shenzhen\":\"深圳\",\"beijing\":\"北京\",\"shanghai\":[{\"zj1\":\"zj11\",\"zj2\":\"zj22\"},\"zjs\"]}";
Console.WriteLine(mStr); //{"shenzhen":"深圳","beijing":"北京","shanghai":[{"zj1":"zj11","zj2":"zj22"},"zjs"]}
JObject mJobject = JObject.Parse(mStr);
string shenzhen = mJobject["shenzhen"].ToString(); //深圳
Console.WriteLine(shenzhen);
string shagnhai = mJobject["shanghai"].ToString(); //[{\"zj1\":\"zj11\",\"zj2\":\"zj22\"},\"zjs\"]
Console.WriteLine(shagnhai);
string zjs = mJobject["shanghai"][1].ToString(); //zjs
Console.WriteLine(zjs);
JToken zjl = mJobject["shanghai"][0];
Console.WriteLine(zjl.ToString()); //{\"zj1\":\"zj11\",\"zj2\":\"zj22\"}
JToken zj1 = zjl["zj1"];
Console.WriteLine(zj1.ToString()); //zj11
Console.ReadKey();
}
}
}
json字符串转实体
参考: https://blog.csdn.net/qq_36694133/article/details/116708853
新建Student类
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
/// <summary>
/// 学生
/// </summary>
public class Student
{
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 班级
/// </summary>
public string Classroom { get; set; }
}
}
json字符串转实体类
using Nancy.Json;
using Newtonsoft.Json.Linq;
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//实体转json字符串
Student mStudent = new Student();
mStudent.Name = "张三";
mStudent.Age = 23;
mStudent.Classroom = "101";
string mStudentStr = new JavaScriptSerializer().Serialize(mStudent);
Console.WriteLine(mStudentStr); //{"name":"张三","age":23,"classroom":"101"}
//json字符串转实体
string mStr1 = "{\"name\":\"李四\",\"age\":22,\"classroom\":\"102\"}";
Student mStudent1 = new JavaScriptSerializer().Deserialize<Student>(mStr1);
//姓名:李四,年龄:22,班级:102.
Console.WriteLine("姓名:{0},年龄:{1},班级:{2}.", mStudent1.Name, mStudent1.Age, mStudent1.Classroom);
Console.ReadKey();
}
}
}
标签:Console,string,c#,json,WriteLine,字符串,using,zj1
From: https://blog.51cto.com/zicl/12167812