我已经和JSON.net合作了一段时间.我已经编写了自定义转换器和自定义合同解析器(通常来自修改SO和Newtonsoft网站上的示例),它们工作正常.
除了例子之外,我面临的挑战是,我什么时候应该使用其中一个(或两个)进行处理.根据我自己的经验,我基本上已经确定合同解决方案更简单了,所以如果我可以用他们做我需要的东西,我会这样做; 否则,我使用自定义JsonConverters.但是,我进一步知道两者有时一起使用,因此概念变得更加不透明.
问题:
我在使用JSON.NET库对从Facebook返回的数据进行反序列化时遇到了一些麻烦.
从简单的墙贴文件返回的JSON看起来像:
{
"attachment":{"description":""},
"permalink":"http://www.facebook.com/permalink.php?story_fbid=123456789"
}
Run Code Online (Sandbox Code Playgroud)
为照片返回的JSON如下所示:
"attachment":{
"media":[
{
"href":"http://www.facebook.com/photo.php?fbid=12345",
"alt":"",
"type":"photo",
"src":"http://photos-b.ak.fbcdn.net/hphotos-ak-ash1/12345_s.jpg",
"photo":{"aid":"1234","pid":"1234","fbid":"1234","owner":"1234","index":"12","width":"720","height":"482"}}
],
Run Code Online (Sandbox Code Playgroud)
一切都很好,我没有问题.我现在遇到一个来自移动客户端的简单墙帖,其中包含以下JSON,现在反序列化失败,只有一个帖子:
"attachment":
{
"media":{},
"name":"",
"caption":"",
"description":"",
"properties":{},
"icon":"http://www.facebook.com/images/icons/mobile_app.gif",
"fb_object_type":""
},
"permalink":"http://www.facebook.com/1234"
Run Code Online (Sandbox Code Playgroud)
这是我反序列化的类:
public class FacebookAttachment
{
public string Name { get; set; }
public string Description { get; set; }
public string Href { get; set; }
public FacebookPostType Fb_Object_Type { get; set; }
public string Fb_Object_Id { get; set; }
[JsonConverter(typeof(FacebookMediaJsonConverter))]
public List<FacebookMedia> { get; set; }
public string Permalink { get; …Run Code Online (Sandbox Code Playgroud) I am trying to deserialize some JSON that contains a value that is sometimes an array, and sometimes a single item. How can I do this with System.Text.Json and JsonSerializer? (This question is inspired by this question for Json.NET by Robert McLaws.)
I have received the following JSON:
[
{
"email": "john.doe@sendgrid.com",
"timestamp": 1337966815,
"category": [
"newuser",
"transactional"
],
"event": "open"
},
{
"email": "jane.doe@sendgrid.com",
"timestamp": 1337966815,
"category": "olduser",
"event": "open"
}
]
Run Code Online (Sandbox Code Playgroud)
And I want to deserialize …
有没有办法在单个操作中序列化从十进制到十进制[]的Json对象属性?
在我的Json产品Feed中,特价商品表示为数组(正常价格/促销价).普通商品只是价格.像这样:
[
{
"product" : "umbrella",
"price" : 10.50,
},
"product" : "chainsaw",
"price" : [
39.99,
20.0
]
}
]
Run Code Online (Sandbox Code Playgroud)
我可以让它工作的唯一方法是,如果我将属性设置为这样的对象:
public class Product
{
public string product { get; set; }
public object price { get; set; }
}
var productList = JsonConvert.DeserializeObject<List<Product>>(jsonArray);
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试使其为decimal [],那么它将在单个十进制值上抛出异常.使它成为一个对象意味着数组值是一个JArray所以我以后必须做一些清理工作,我的应用程序中的其他映射要求属性类型是准确的所以我必须将其映射到未映射的属性然后初始化另一个属性没什么大不了的,但命名有点混乱.
对象是这里唯一的选择还是我可以使用序列化程序做一些魔术,要么将单个值添加到数组,要么将第二个值添加到单独的属性以获得特价?
我正在使用Yahoo fantasy sports api.我得到这样的结果:
"player": [
{
...
"eligible_positions": {
"position": "QB"
},
...
},
{
...
"eligible_positions": {
"position": [
"WR",
"W/R/T"
]
},
...
},
Run Code Online (Sandbox Code Playgroud)
我怎么能反序化呢?
我的代码看起来像这样:
var json = new JavaScriptSerializer();
if (response != null)
{
JSONResponse JSONResponseObject = json.Deserialize<JSONResponse>(response);
return JSONResponseObject;
}
Run Code Online (Sandbox Code Playgroud)
在我的JSONResponse.cs文件中:
public class Player
{
public string player_key { get; set; }
public string player_id { get; set; }
public string display_position { get; set; }
public SelectedPosition selected_position { get; set; }
public …Run Code Online (Sandbox Code Playgroud) 我想知道是否可以反序列化可能是对象或数组的JSON对象.
与此问题类似:杰克逊反序列化对象或数组
但是使用JSON.Net.
例
{
"response": {
"status":"success",
// Could be either a single object or an array of objects.
"data": {
"prop":"value"
}
// OR
"data": [
{"prop":"value"},
{"prop":"value"}
]
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用Newtonsoft.Json处理一些返回给我的JSON数据.根据我的要求,我可以得到一些看起来像:
{
"TotalRecords":2,
"Result":
[
{
"Id":24379,
"AccountName":"foo"
},
{
"Id":37209,
"AccountName":"bar"
}
],
"ResponseCode":0,
"Status":"OK",
"Error":"None"
}
Run Code Online (Sandbox Code Playgroud)
要么
{
"Result":
{
"Id":24379,
"AccountName":"foo"
},
"ResponseCode":0,
"Status":"OK",
"Error":"None"
}
Run Code Online (Sandbox Code Playgroud)
因此,有时"结果"是结果数组,或者"结果"可能是单个响应.
我尝试使用如何使用JSON.net处理同一属性的单个项目和数组的答案,但我仍然得到错误.
特别是我得到了一个
Newtonsoft.json.jsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List'...
Run Code Online (Sandbox Code Playgroud)
定制转换器看起来像:
public class SingleOrArrayConverter<T> : JsonConverter
{
public override bool CanConvert(Type objecType)
{
return (objecType == typeof(List<T>));
}
public override object ReadJson(JsonReader reader, Type objecType, object existingValue,
JsonSerializer serializer)
{
JToken token = JToken.Load(reader); …Run Code Online (Sandbox Code Playgroud) 我们有以下课程:
class Foo
{
public object Any;
}
Run Code Online (Sandbox Code Playgroud)
该类接受该字段中的任何内容Any.
我打电话的时候:
JsonConvert.DeserializeObject<Foo>("{any: 5}")
Run Code Online (Sandbox Code Playgroud)
Any包含System.Int64.
但是,当我打电话时:
JsonConvert.DeserializeObject<Foo>("{any: [5]}")
Run Code Online (Sandbox Code Playgroud)
Any包含Newtonsoft.Json.Linq.JArray.
如何配置JSON.NET以便在这种情况下 Any包含List<object>?
澄清:
可以有任何东西,我可以打电话:
JsonConvert.DeserializeObject<Foo>("{any: 'c'}")
Run Code Online (Sandbox Code Playgroud)
要么
JsonConvert.DeserializeObject<Foo>("{any: ['c', 5]}")
Run Code Online (Sandbox Code Playgroud)
更多说明:
我想以某种方式告诉JSON.NET(可能使用JsonSerializerSettings):
当您遇到
objectJSON包含数组时,将其反序列化为(例如)List<object>.
我正在使用此调用从 JSON 中读取对象列表:
Rootobject userInfo = JsonConvert.DeserializeObject<Rootobject>(File.ReadAllText(strFileName));
Run Code Online (Sandbox Code Playgroud)
但我得到了一个例外Cannot deserialize the current JSON array。如果类对象之一中的数组之一为空。只要有数据,一切正常。
下面是一个 JSON 的例子,它导致了反序列化器:
这是 Venue 对象的正常数据类型:
"venue": {
"venue_id": 696895,
"venue_name": "Blackfinn Ameripub",
"venue_slug": "blackfinn-ameripub",
"primary_category": "Food",
"parent_category_id": "4d4b7105d754a06374d81259",
"categories": {
"count": 1,
"items": [
{
"category_name": "American Restaurant",
"category_id": "4bf58dd8d48988d14e941735",
"is_primary": true
}
]
},
"is_verified": false
},
Run Code Online (Sandbox Code Playgroud)
这是导致异常的原因,一个空数组:
"venue": [
],
Run Code Online (Sandbox Code Playgroud)
我已经使用了试图JsonSerializerSettings选择,包括DefaultValueHandling,NullValueHandling和MissingMemberHandling,但他们都不来防止错误。
知道如何反序列化 JSON 并忽略数据中的任何空数组吗?我希望它可以处理任何空数组,而不仅仅是上面的 object 示例Venue。
发现新问题 - 03/17/2018 <<
嗨,下面的转换器一直工作得很好,但是我从我的 json …
我有这样的代码:
var json = GetJsonData(path);
JObject event_dates_data = JObject.Parse(json);
var event_dates_list = JObject.Parse(event_dates_data["document"]["date"].ToString());
var event_dates = JsonConvert.DeserializeObject<List<EventDate>>(event_dates_list.ToString());
Run Code Online (Sandbox Code Playgroud)
Json 可能包含一个数组对象(例如“date:[{},{},{}]”)或仅包含一个(例如“date:{}”)
Json 看起来像这样:
{
"document": {
"result": "success",
"resultcode": "000000",
"note": null,
"totaldates": "1",
"date": {
"date_id": "351314",
"live": "n",
"datestart": "2012-03-07",
"dateend": "2015-03-07",
"timestart": "12:00",
"timeend": "14:00",
"date_available": "10000"
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者:
{
"document": {
"result": "success",
"resultcode": "000000",
"note": null,
"totaldates": "4",
"date": [
{
"date_id": "346022",
"live": "n",
"datestart": "2011-02-19",
"dateend": "2011-02-19",
"timestart": "12:00",
"timeend": "14:00",
"date_available": "10000" …Run Code Online (Sandbox Code Playgroud)