我目前正在使用一个控制台应用程序,我正在使用HttpClient与Apache CouchDB数据库进行交互。我正在使用这篇文章:http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
当我通过PostAsJsonSync序列化并将文档发送到我的数据库时,我想忽略我的类中的null属性,但我不确定如何:
public static HttpResponseMessage InsertDocument(object doc, string name, string db)
{
HttpResponseMessage result;
if (String.IsNullOrWhiteSpace(name)) result = clientSetup().PostAsJsonAsync(db, doc).Result;
else result = clientSetup().PutAsJsonAsync(db + String.Format("/{0}", name), doc).Result;
return result;
}
static HttpClient clientSetup()
{
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("**************", "**************");
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("*********************");
//needed as otherwise returns plain text
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
这是我正在序列化的课程....
class TestDocument
{
public string Schema { get; set; }
public long Timestamp { get; set; }
public int Count { get; set; }
public string _rev { get; set; }
public string _id { get; set; } - would like this to be ignored if null
}
任何帮助都非常感激。
答案 0 :(得分:13)
假设您使用Json.NET序列化对象,则应使用JsonProperty属性的NullValueHandling属性
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
查看这篇精彩的article和online help了解更多详情
答案 1 :(得分:11)
如果您需要针对您要发送的所有类的所有属性执行此行为(这正是导致我提出这个问题的情况),我认为这会更清晰:
using ( HttpClient http = new HttpClient() )
{
var formatter = new JsonMediaTypeFormatter();
formatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
TestDocument value = new TestDocument();
HttpContent content = new ObjectContent<TestDocument>( value, formatter );
await http.PutAsync( url, content );
}
这样就无需为您的课程添加属性,您也不必手动序列化所有值。
答案 2 :(得分:4)
使用HttpClient.PostAsync
JsonMediaTypeFormatter jsonFormat = new JsonMediaTypeFormatter();
jsonFormat.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;
jsonFormat.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
HttpResponseMessage res = c.PostAsync<T>(url, TObj, jsonFormat).Result;
答案 3 :(得分:3)
我不确定你现在可以使用PutAsJsonAsync
来做到这一点。 Json.NET可以做到这一点,如果你能够使用它,并且如果它有帮助就存在NuGet包。如果你可以使用它,我会重写InsertDocument
函数看起来像:
public static HttpResponseMessage InsertDocument(object doc, string name, string db)
{
HttpResponseMessage result;
string json = JsonConvert.SerializeObject(doc, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
if (String.IsNullOrWhiteSpace(name)) result = clientSetup().PostAsync(db, new StringContent(json, null, "application/json")).Result;
else result = clientSetup().PutAsync(db + String.Format("/{0}", name), new StringContent(json, null, "application/json")).Result;
return result;
}