简体   繁体   English

防止在json中序列化属性名称

[英]Prevent serialize property name in json

I have two classes. 我有两节课。 First one is: 第一个是:

public int id { get; set; }
public List<AnotherClass> field1 { get; set; }

And the second one is 第二个是

public class AnotherClass
{
    [JsonIgnore]
    public int id { get; set; }
    public string subfieldValue { get; set; }
}

when I make object from these classes and serialize them I get below JSON from them 当我从这些类中创建对象并对其进行序列化时,我从它们下面得到了JSON

{
    "id" : "1",
    "field1": [
         {
             "subfieldValue":"value1"
         },
         {
             "subfieldValue":"value2"
         }
     ]
 }

But I need below JSON how can I do that? 但是我需要在JSON下执行该操作? Also I can't use List<string> for field1 type because I want to save this values to database with Entity Framework 另外,我不能将List<string>用于field1类型,因为我想使用实体框架将此值保存到数据库中

{
    "id" : "1",
    "field1": ["value1", "value2"]
}
public int id { get; set; }
[JsonIgnore]
public List<AnotherClass> field1s { get; set; }
public List<string> field1
{
    get{return field1s.Select(f=>f. subfieldValue).ToList();}
    set{}
}

Also you probably should maintain the common C# naming convention like Id instead of id and change the json name through attribute with whatever you like in your json. 同样,您可能应该维护Id之类的通用C#命名约定,而不是id并通过json中的任意属性通过属性更改json名称。

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

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