GVKun编程网logo

将JSON字符串反序列化为指定的.NET对象类型(json反序列化成对象)

11

对于想了解将JSON字符串反序列化为指定的.NET对象类型的读者,本文将提供新的信息,我们将详细介绍json反序列化成对象,并且为您提供关于.net–将json反序列化为c#中的匿名对象、c#–将js

对于想了解将JSON字符串反序列化为指定的.NET对象类型的读者,本文将提供新的信息,我们将详细介绍json反序列化成对象,并且为您提供关于.net – 将json反序列化为c#中的匿名对象、c# – 将json twitter字符串反序列化为对象、c# – 将JSON反序列化为字符串数组、c# – 用Json.Net反序列化,将子对象反序列化为字符串/类似的持有json?的有价值信息。

本文目录一览:

将JSON字符串反序列化为指定的.NET对象类型(json反序列化成对象)

将JSON字符串反序列化为指定的.NET对象类型(json反序列化成对象)

前言:

  关于将JSON字符串反序列化为指定的.NET对象类型数据常见的场景主要是关于网络请求接口,获取到请求成功的响应数据。本篇主要讲的的是如何通过使用Newtonsoft.Json中的JsonConvert.DeserializeObject<T>(string value)方法将对应的JSON字符串转化为指定的.NET对象类型数据。

方法一、在项目中定义对应的对象参数模型,用于映射反序列化出来的参数(复杂JSON字符串数据推荐使用):

如下是一组.NET后台请求接口成功获取到的复杂的JSON字符串数据:

{
    "id": "123456",
    "result": {
        "data": {
            "liveToken": "zxcvbnm",
            "liveStatus": 1,
            "liveType": 1,
            "deviceId": "1234567890",
            "channelId": "0",
            "coverUpdate": 30,
            "streams": [{
                "hls": "zxcv.safd",
                "coverUrl": "http://asdaf",
                "streamId": 0
            }],
            "job": [{
                "status": true,
                "period": "always"
            }]
        },
        "code": "0",
        "msg": "操作成功"
    }
}

根据该组JSON字符串格式数据定义对应的对象参数模型:

public class BindDeviceLiveHttpsResponse
    {
        public BindDeviceLiveHttpsResult result { get; set; }

        public string id { get; set; }
    }

    public class BindDeviceLiveHttpsResult
    {
        public BindDeviceLiveHttpsData data { get; set; }

        public string code { get; set; }

        public string msg { get; set; }
    }


    public class BindDeviceLiveHttpsData
    {
        public string liveToken { get; set; }

        public int liveStatus { get; set; }

        public int liveType { get; set; }

        public string deviceId { get; set; }

        public string channelId { get; set; }

        public int coverUpdate { get; set; }

        public List<BindDeviceLiveHttpsStreams> streams { get; set; }

        public List<BindDeviceLiveHttpsJob> job { get; set; }

    }

    public class BindDeviceLiveHttpsStreams
    {
        public string hls { get; set; }

        public string coverUrl { get; set; }

        public int streamId { get; set; }

    }

    public class BindDeviceLiveHttpsJob
    {
        public bool status { get; set; }

        public string period { get; set; }
    }

通过JsonConvert.DeserializeObject<自定义模型>(string value)反序列化:

var resultContext = JsonConvert.DeserializeObject<GetLiveStreamInfoResponse>(JSON字符串数据);
//最后我们可以通过对象点属性名称获取到对应的数据

 

方法二、直接将JSON字符串格式数据反序列化转化为字典数据(简单JSON字符串数据推荐使用):

如下一组简单的JSON字符串格式数据:

{
    "id": "123456",
    "code": "0",
    "msg": "操作成功"
}

通过JsonConvert.DeserializeObject<Dictionary<string, object>>(string value)方法反序列化为字典数据,在通过key访问对应的value的值:

var resultContext=JsonConvert.DeserializeObject<Dictionary<string, object>>(JSON格式数据);

//获取msg的值:
var msg=resultContext["msg"];

输出为:操作成功

 

.net – 将json反序列化为c#中的匿名对象

.net – 将json反序列化为c#中的匿名对象

如何将一串json格式的数据转换为匿名对象?

解决方法

C#4.0添加了可以使用的动态对象.看看 this.

c# – 将json twitter字符串反序列化为对象

c# – 将json twitter字符串反序列化为对象

使用下面的URL我试图拉动一个特定的屏幕名称有效的追随者.当我尝试将代码反序列化为一个ojbect时,我会在下面找到任何想法的错误消息.我也把代码用于Json类型..我想获得位置归档.我已经发布用户本身就是一个对象.所以我可以得到一个例子,它将让我对初始对象进行脱盐,然后将对象放入其中.

URL =“https://api.twitter.com/1.1/followers/list.json?\u0026amp;screen_name=\”will insert here”

反序列化为objec代码

var result = JsonConvert.DeserializeObject<List>(FollowerData)

Json类型代码

public class Follower
{

[JsonProperty("created_at")]
public string CreatedAt { get; set; }

[JsonProperty("id")]
public string Id { get; set; }

[JsonProperty("id_str")]
public string IdStr { get; set; }

[JsonProperty("name")]
public string Name { get; set; }

[JsonProperty("screen_name")]
public string ScreenName { get; set; }

[JsonProperty("location")]
public bool Location { get; set; }

[JsonProperty("description")]
public string Description { get; set; }

}

错误信息

{“Cannot deserialize the current JSON object (e.g.
{\”name\”:\”value\”}) into type
‘System.Collections.Generic.List`1[OAuthTwitterWrapper.JsonTypes.FollowerUsers]’
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.\r\nTo fix this error either change the JSON to a JSON array
(e.g. [1,3]) or change the deserialized type so that it is a normal
.NET type (e.g. not a primitive type like integer,not a collection
type like an array or List) that can be deserialized from a JSON
object. JsonObjectAttribute can also be added to the type to force it
to deserialize from a JSON object.\r\nPath ‘users’,line 1,position
9.”}

Json String Examplt

{
    "users": [
        {
            "id": 219566993,"id_str": "219566993","name": "belenastorgano","screen_name": "anna_belenn_","location": "CapitalFederal,Argentina","description": "Mesientonomade,todav\\u00edanotengounlugarfijodondevivir.-","url": null,"entities": {
                "description": {
                    "urls": []
                }
            },"protected": true,"followers_count": 44,"friends_count": 64,"listed_count": 0,"created_at": "ThuNov2506: 28: 12+00002010","favourites_count": 1,"utc_offset": -10800,"time_zone": "BuenosAires","geo_enabled": true,"verified": false,"statuses_count": 207,"lang": "es","contributors_enabled": false,"is_translator": false,"profile_background_color": "599E92","profile_background_image_url": "http: \\/\\/a0.twimg.com\\/images\\/themes\\/theme18\\/bg.gif","profile_background_image_url_https": "https: \\/\\/si0.twimg.com\\/images\\/themes\\/theme18\\/bg.gif","profile_background_tile": false,"profile_image_url": "http: \\/\\/a0.twimg.com\\/profile_images\\/378800000326157070\\/e91b8fd8e12eda0a7fa350dcd286c56a_normal.jpeg","profile_image_url_https": "https: \\/\\/si0.twimg.com\\/profile_images\\/378800000326157070\\/e91b8fd8e12eda0a7fa350dcd286c56a_normal.jpeg","profile_link_color": "E05365","profile_sidebar_border_color": "EEEEEE","profile_sidebar_fill_color": "F6F6F6","profile_text_color": "333333","profile_use_background_image": true,"default_profile": false,"default_profile_image": false,"following": null,"follow_request_sent": null,"notifications": null
        }
    ],"next_cursor": 1443863551966642400,"next_cursor_str": "1443863551966642309","prevIoUs_cursor": 0,"prevIoUs_cursor_str": "0"
}

解决方法

the only field i need is the location in the user table

你不需要任何类来从你的json中获取一些字段.只是利用动态

dynamic dynObj = JsonConvert.DeserializeObject(json); 
Console.WriteLine(dynObj.users[0].location);

c# – 将JSON反序列化为字符串数组

c# – 将JSON反序列化为字符串数组

我刚刚开始涉足C#,我现在已经对 JSON反序列化进行了一段时间的讨论.我正在使用Newtonsoft.Json库.我期待一个字典数组的json响应
[{"id":"669","content":" testing","comments":"","ups":"0","downs":"0"},{"id":"482","content":" test2","downs":"0"}]

现在我有:(注意:下载只是一个包含json字符串的字符串)

string[] arr = JsonConvert.DeserializeObject<string[]>(download);

我尝试了很多不同的方法,每个方法都失败了.解析这种类型的json有标准的方法吗?

解决方法

你有一个对象数组而不是字符串.创建一个映射属性的类并反序列化为,
public class MyClass {
    public string id { get; set; }
    public string content { get; set; }
    public string ups { get; set; }
    public string downs { get; set; }
}

MyClass[] result = JsonConvert.DeserializeObject<MyClass[]>(download);

JSON中只有几种基本类型,但学习和识别它们很有帮助.对象,数组,字符串等http://www.json.org/和http://www.w3schools.com/json/default.asp是很好的入门资源.例如,JSON中的字符串数组看起来像,

["One","Two","Three"]

c# – 用Json.Net反序列化,将子对象反序列化为字符串/类似的持有json?

c# – 用Json.Net反序列化,将子对象反序列化为字符串/类似的持有json?

我正在尝试使用Json创建配置文件,该文件将保存各种类型对象的配置.

考虑这个文件:

{
    "cameras": [
        {
            "type": "Some.Namespace.CameraClass","assembly": "Some.Assembly","configuration": {
                "ip": "127.0.0.1","port": 8080
            }
        }
    ]
}

在运行时,我将使用两个“类型”和“程序集”属性来构造支持特定接口的对象,然后我想将配置加载到该对象中.

但是,在编译时我不知道“配置”将映射到的类型.我想将它保留为json“属性”并将其提供给相机对象,然后让该对象将json反序列化为正确的类型.

因此,我想将包含特定相机类型配置的配置文件的一部分“随身携带”到对象本身,然后让它处理它,像我一样把它当作黑盒子处理它.应该保留该部分的结构,因为在为每个摄像机实现创建配置类型时我想要完全保真,甚至在必要时添加子对象.

对于这个特定的相机,我会配置一个IP地址和一个端口,对于其他一些相机我需要授权数据,而对于其他一些相机则完全不同.

我希望保持这种配置的属性能够直接获取Json,仍然是一个字符串.

这可能吗?

这是一个有一些位注释掉的LINQPad示例:

void Main()
{
    const string configurationFile = @"[
    {
        ""type"": ""UserQuery+Camera1"",""configuration"": { ""id"": 10 }
    },{
        ""type"": ""UserQuery+Camera2"",""configuration"": { ""name"": ""The second camera"" }
    }
]";
    var cameras = JsonConvert.DeserializeObject<Camera[]>(configurationFile);
    foreach (var camera in cameras)
    {
        var type = Type.GetType(camera.Type);
        var instance = Activator.CreateInstance(type,new object[0]) as ICamera;
        // instance.Configure(camera.Configuration);
    }
}

public class Camera
{
    public string Type { get; set; }
    public JObject Configuration { get; set; }
}

public interface ICamera
{
    void Configure(string json);
}

public class Camera1 : ICamera
{
    private class Configuration
    {
        public int Id { get; set; }
    }

    public void Configure(string json)
    {
        JsonConvert.DeserializeObject<Configuration>(json).Dump();
    }
}

public class Camera2 : ICamera
{
    private class Configuration
    {
        public string Name { get; set; }
    }

    public void Configure(string json)
    {
        JsonConvert.DeserializeObject<Configuration>(json).Dump();
    }
}

两个注释掉的位,即Camera类中的属性,以及对Configure方法的调用,都是我想要的.

有什么东西我可以标记该属性,或者我可以为该属性选择的其他类型,这将使​​这工作吗?

我知道我可以使属性动态化,这会将JObject填入其中,但是每个相机实现的每个Configure方法都必须处理JObject而不是已知的非动态类型.

解决方法

看起来如果你使用JObject类型的属性,它会解析但保留JSON:
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;    

public class Foo
{
    public string Name { get; set; }
    public int Age { get; set; }
    public JObject Configuration { get; set; }
}

public class Test
{
   public static void Main()
   {
       var json = File.ReadAllText("test.json");
       var foo = JsonConvert.DeserializeObject<Foo>(json);
       Console.WriteLine(foo.Configuration);
   }

}

Test.json:

{
  "name": "Jon","age": 10,"configuration": {
    "ip": "127.0.0.1","port": 8080
  }
}

输出:

{
  "ip": "127.0.0.1","port": 8080
}

我怀疑你可以直接从JObject反序列化,但如果你真的想,你总是可以将它转换回字符串.

今天关于将JSON字符串反序列化为指定的.NET对象类型json反序列化成对象的讲解已经结束,谢谢您的阅读,如果想了解更多关于.net – 将json反序列化为c#中的匿名对象、c# – 将json twitter字符串反序列化为对象、c# – 将JSON反序列化为字符串数组、c# – 用Json.Net反序列化,将子对象反序列化为字符串/类似的持有json?的相关知识,请在本站搜索。

本文标签: