简体   繁体   English

在.NET中序列化JSON

[英]Serializing JSON in .NET

I have wrote a basic web service using .net which I intend to use in a mobile app. 我已经使用.net编写了一个基本的Web服务,打算在移动应用程序中使用它。 It currently outputs Json however the structure it not quite what I need. 目前,它输出的是Json,但结构并不完全符合我的需要。

The models I've created 我创建的模型

[DataContract]
class PoiList
{
    [DataMember]
    public List<Poi> Pois { get; set; }
}

[DataContract]
class Poi
{
    [DataMember]
    public string title { get; set; }
    [DataMember]
    public string latitude { get; set; }
    [DataMember]
    public string longitude { get; set; }
}

Then i added some test data: 然后我添加了一些测试数据:

PoiList poiList = new PoiList
    {
        Pois = new List<Poi>()
    };

    Poi p = new Poi
    {
        title = "whatever",
        latitude = "-2.45554",
        longitude = "52.5454645"
    };

    poiList.Pois.Add(p);

    p = new Poi
    {
        title = "weeee",
        latitude = "-2.45554",
        longitude = "52.5454645"
    };

    poiList.Pois.Add(p);

    string ans = JsonConvert.SerializeObject(poiList, Formatting.Indented);

This is what the returned string looks like: 返回的字符串如下所示:

{ "Pois": [ { "title": "shit", "latitude": "-2.45554", "longitude": "52.5454645" }, { "title": "weeee", "latitude": "-2.45554", "longitude": "52.5454645" } ] }

...and this is what I want the outputted Json to look like: ...这就是我想要输出的Json的样子:

string TempString = @"{ ""pois"":
                        [{ ""poi"": 
                            {
                                ""title"": ""Test title"",  
                                ""latitude"": ""-2.4857856"",
                                ""longitude"": ""54.585656""
                            }},
                        { ""poi"":
                            {
                                ""title"": ""Halfords"",
                                ""latitude"": ""-2.575656"",
                                ""longitude"": ""53.5867856""
                    }}]}";

Basically the only difference being the "poi" next to each object in the list. 基本上,唯一的区别是列表中每个对象旁边的“ poi”。 Is there a simple way to include this? 有没有简单的方法可以包含此内容? I should add I am using the newtonsoft.json package. 我应该添加我正在使用newtonsoft.json包。

I would suggest you go with the JSON that's being generated, as your target JSON contains unnecessary objects, IMO. 我建议您使用正在生成的JSON,因为目标JSON包含不必要的对象IMO。

Your target JSON has an object with a single field "pois", which contains a list of objects, each with a single field "poi" that contains an object with the fields "title", "latitude", and "longitude". 您的目标JSON有一个带有单个字段“ pois”的对象,该对象包含一个对象列表,每个对象都有一个单个字段“ poi”,其中包含一个带有字段“ title”,“ latitude”和“ longitude”的对象。

To access a single title field, you would need to do the following: 要访问单个标题字段,您需要执行以下操作:

poisObj.pois[0].poi.title

If you go with the JSON that's generated by your object structure, you would access a single title field like so: 如果使用对象结构生成的JSON,则可以访问单个标题字段,如下所示:

poisObj.pois[0].title

That having been said, if you absolutely must target that JSON structure, you'll need another DataContract object, as follows: 话虽如此,如果您绝对必须以该JSON结构为目标,则需要另一个DataContract对象,如下所示:

[DataContract]
class PoiList
{
    [DataMember]
    public List<PoiPoi> Pois { get; set; }
}
[DataContract]
class PoiPoi
{
    [DataMember]
    public Poi poi { get; set; }
}

[DataContract]
class Poi
{
    [DataMember]
    public string title { get; set; }
    [DataMember]
    public string latitude { get; set; }
    [DataMember]
    public string longitude { get; set; }
}

Go with the default structure the only thing the "poi" gives you is what "type" the object is, which JSON doesn't really have a concept of. 使用默认结构,“ poi”唯一给您的就是对象的“类型”,而JSON并没有这个概念。 If you want to include type information, try :- 如果要包括类型信息,请尝试:-

 var jsonSerializerSettings = new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Objects,
                    TypeNameAssemblyFormat = FormatterAssemblyStyle.Full,                
                };
 var json = JsonConvert.SerializeObject(o, Formatting.None, jsonSerializerSettings);

this will give you a field _type_ which is useful especially if you have a list of various types of objects. 这将为您提供一个_type_字段,该字段特别有用,如果您具有各种类型的对象的列表。 Json.Net then knows how to recreate the objects using this _type_ field. 然后,Json.Net知道如何使用此_type_字段重新创建对象。

No need to declare many tiny classes just to output a json string. 无需声明许多小类即可输出json字符串。 You can create an anonymous object to serialize like below: 您可以创建一个匿名对象以进行序列化,如下所示:

var obj = new { pois = new List<object>() };
obj.pois.Add(new { poi = new {title = "Test title", latitude = "-2.4857856", longitude = "54.585656" } });
obj.pois.Add(new { poi = new {title = "Halfords"  , latitude = "-2.4857856", longitude = "53.5867856" } });

string json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);

Console.WriteLine(json);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM