在C#开发的过程中,需要将json解析成实体对象,方便使用(通过实体打点调用,例:user.username)

在.framework 3.5以上,可以使用如下方法

首先要定义一个实体类

   public class Person
    {
        private string name;
        public string UserName
        {
            get { return name; }
            set { name = value; }
        }
        private int age;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
    }
可以使用JavaScriptSerializer方法来转换json

            string jsonString = "{\"password\":\"a123456\",\"UserName\":\"小王\",\"Age\": 26}";(可以不和实体类匹配,有测显示,没有也没有问题)
            JavaScriptSerializer js = new JavaScriptSerializer();
            userinfo user = js.Deserialize<Person>(jsonString);
            label1.Text = user.Username;


以上就为在winform的label1的内容替换成 小王

但是,这个是要使用.framework3.5以上的版本,

使用.framework3.5以下(比如用的最多的2.0)就不能使用上面的方式,

            string jsonString = "{\"passwo\":\"a123456\",\"UserName\":\"小王\",\"Age\": 26}";
            Person user = (Person)JsonConvert.DeserializeObject(jsonString, typeof(Person));
            label1.Text = user.UserName;
上面的方法和framework4.0的效果是一样的

但是需要引入第三方库Newtonsoft.Json

GitHub 加速计划 / js / json
58
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
b451735f Bumps [lukka/get-cmake](https://github.com/lukka/get-cmake) from 4.0.2 to 4.0.3. - [Release notes](https://github.com/lukka/get-cmake/releases) - [Commits](https://github.com/lukka/get-cmake/compare/ea004816823209b8d1211e47b216185caee12cc5...6b3e96a9bc9976b8b546346fdd102effedae0ca8) --- updated-dependencies: - dependency-name: lukka/get-cmake dependency-version: 4.0.3 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 1 天前
568b708f Bumps [step-security/harden-runner](https://github.com/step-security/harden-runner) from 2.12.0 to 2.12.1. - [Release notes](https://github.com/step-security/harden-runner/releases) - [Commits](https://github.com/step-security/harden-runner/compare/0634a2670c59f64b4a01f0f96f84700a4088b9f0...002fdce3c6a235733a90a27c80493a3241e56863) --- updated-dependencies: - dependency-name: step-security/harden-runner dependency-version: 2.12.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 6 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐