【问题标题】:How to use JSON.net to serial objects but not strings如何使用 JSON.net 串行对象而不是字符串
【发布时间】:2018-09-15 14:03:03
【问题描述】:

我正在寻找这个代码:https://dotnetfiddle.net/80dz3V

使用系统; 使用 Newtonsoft.Json;

public class Program
{

    public class Product
    {
        public string Name {get; set;}
        public DateTime Expiry {get; set;}
        public string[] Sizes {get; set;}
    }

    public void Main()
    {
        Product product = new Product();
        product.Name = "Apple";
        product.Expiry = new DateTime(2008, 12, 28);
        product.Sizes = new string[] { "Small" };

        string json = JsonConvert.SerializeObject(product);
        Console.WriteLine(json);

        object str = "test";


        json = JsonConvert.SerializeObject(str);
        Console.WriteLine(json);
    }
}

正确处理Product,但只返回test 而不是"test"

输出:

{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small"]}
"test"

想要的输出

{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small"]}
test

我知道我可以只使用包装器并检查 as,但我很好奇是否有任何可用的 JSON.net 选项可以完成此操作?

【问题讨论】:

  • 我不会期望任何 - SerializeObject 旨在返回有效的 JSON,而未加引号的字符串就是无效的 JSON。这是一个奇怪的要求IMO。 (所以如果我是你,如果你真的有这个奇怪的要求,我会写一个包装器。)
  • REST 服务很奇怪,作为其发布参数的一部分,它接受一个值(1,2,3,test)或一个 json 对象。 (version=2&things={ "x": [1, 2, 3] }) 但我同意,这是一个奇怪的请求,也许包装器更能传达意图
  • 使用JRaw 代替string,如Get Raw json string in Newtonsoft.Json LibraryJson.NET - prevent re-serializing an already-serialized property 所示。但是不带引号的字符串testinvalid JSON,所以除非您事先知道该字符串是格式正确的JSON,否则我实际上不会这样做。分叉小提琴:dotnetfiddle.net/mR5WJ7

标签: c# json.net


【解决方案1】:

如果您的产品是 viewModel,也许您可​​以使用 automapper 像 Json 一样返回它,或者您可以使用 newtonsoft 的以下方法

var jsonObject = new JObject
    {
         {"Property1", Obj.Prop1},
         {"Property2", Obj.Prop1 },
         {"Property3", Obj.Prop1 },
         {"Property4", Obj.Prop1 }
    };

例如结果是:

{"Property1": "Test", "Property2": 1, "Property3": "ABC123", "Property4": 123.21 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2011-08-06
    • 2014-02-08
    • 1970-01-01
    相关资源
    最近更新 更多