检测JSON空性和ommitted属性之间的区别 [英] Detecting the difference between null property and ommitted property in JSON

查看:201
本文介绍了检测JSON空性和ommitted属性之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RESTful Web服务,它接收JSON和它使用DataContractJsonSerializer deserialises它变成一个C#类,虽然这是可以改变的。

I have a RESTful webservice which receives JSON and it deserialises it into a c# class using the DataContractJsonSerializer, though this can be changed.

它的目的是更新资源领域

Its purpose is to update fields on a resource

例如:

{
    "firstName" : "Martin"
}

我不一定要更新所有的领域,我希望能找到一种方法来检测它们并没有未指定的JSON领域。

I don't necessarily want to update all the fields, and I was hoping to find a way to detect fields which are and are not unspecified in the JSON.

我不能找到一个办法然而,做到这一点,因为我不知道怎么跟一个未指定的字段,应更新为空字段之间的区别

I can't find a way to do this however because I don't know how to tell the difference between an unspecified field and a field which should be updated to null

例如:(不更新任何字段):

e.g: (don't update any fields):

{}

VS:(更新名字字段为空)

vs: (update the firstName field to null)

{
    "firstName" : null
}

什么是approch这一点的最好方法是什么?

What is the best way to approch this?

推荐答案

我想你可以使用一些随机字符串初始化的字段

I think you can use a field initialized with some random string

public class TestClass
{
    public string firstName = "some string";
}

如果您反序列化使用 {名字:空} ,名字将为空。如果反序列化使用 {} 的firstName不会改变(一些字符串

If you deserialize using {"firstName" : null}, firstName will be null. if you deserialize using {} firstName won't change (some string)

PS:请不要使用 DataContract 数据成员如果您使用的是DataContractJsonSerializer属性

PS: Don't use DataContract or DataMember attributes if you are using DataContractJsonSerializer

这篇关于检测JSON空性和ommitted属性之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆