像这样的数组:
server {
charset UTF-8;
listen 80;
listen [::]:80;
server_name www.mysite.com;
access_log /var/log/nginx/host.access.log main;
error_log /var/log/nginx/host.error.log main;
# define a root location variable and assign a value
set $rootLocation /usr/share/nginx/html;
# define www.mysite.com landing page to the static index.html page
location / {
root rootLocation;
index index.html index.htm;
}
# define error page to the static index.html page
error_page 404 /index.html;
location = /index.html {
root rootLocation;
internal;
}
# redirect server error pages to the static index.html page
error_page 500 502 503 504 /index.html;
location = /index.html {
root rootLocation;
internal;
}
# redirect www.mysite.com/admin to localhost
# /admin or /admin/ or /admin/**** must be redirect to localhost
location /admin {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass "http://127.0.0.1:3000";
}
# redirect www.mysite.com/user to localhost
# /user or /user/ or /user/**** must be redirect to localhost
location /user {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass "http://127.0.0.1:3001";
}
}
通过JSON.NET序列化为:
[0,“”,null]
我需要强制JSON.NET获得下一个结果(类型默认值根本没有值):
[,,]
有什么办法可以存档吗?
答案 0 :(得分:2)
public static class JsonHelper
{
public static string SerializeToMinimalJson(object obj)
{
return JToken.FromObject(obj).RemoveEmptyChildren().ToString();
}
public static JToken RemoveEmptyChildren(this JToken token)
{
if (token.Type == JTokenType.Object)
{
JObject copy = new JObject();
foreach (JProperty prop in token.Children<JProperty>())
{
JToken child = prop.Value;
if (child.HasValues)
{
child = child.RemoveEmptyChildren();
}
if (!child.IsNullOrEmpty())
{
copy.Add(prop.Name, child);
}
}
return copy;
}
else if (token.Type == JTokenType.Array)
{
JArray copy = new JArray();
foreach (JToken item in token.Children())
{
JToken child = item;
if (child.HasValues)
{
child = child.RemoveEmptyChildren();
}
if (!child.IsNullOrEmpty())
{
copy.Add(child);
}
}
return copy;
}
return token;
}
public static bool IsNullOrEmpty(this JToken token)
{
return token == null ||
(token.Type == JTokenType.Array && !token.HasValues) ||
(token.Type == JTokenType.Object && !token.HasValues) ||
(token.Type == JTokenType.String && token.ToString() == String.Empty) ||
(token.Type == JTokenType.Null);
}
}
以上课程将删除空孩子。 然后,您可以像这样序列化您的对象:
var json = JsonHelper.SerializeToMinimalJson(obj);