简体   繁体   English

Json 序列化/合同解析器 - 需要序列化 object 因此包含的键值对列表转换为同一级别的名称值对

[英]Json Serialization/Contract Resolvers - Need to serialize object so contained list of key value pairs is converted to name value pairs at same level

Since I'm having a hard time explain my question, I made a fiddle.由于我很难解释我的问题,所以我做了一个小提琴。 https://dotnetfiddle.net/aa18qT https://dotnetfiddle.net/aa18qT

I have a class that contains a list of another class with only two properties a key and a value.我有一个 class 包含另一个 class 的列表,其中只有两个属性一个键和一个值。 Alternatively I could use a dictionary.或者,我可以使用字典。 I am serializing this to json.我将其序列化为 json。

Currently I have目前我有

{
  "part":1,
  "quant":2,
  "comments":"something",
  "CustomFields": [
  {
    "key":"groc1",
    "value":"truffles"
  },
  {
    "key":"groc 2",
    "value":"some thing"
  }
 ]
}

And what I want is而我想要的是

{
   "part":1,
   "quant":2,
   "comments":"something",
   "groc 1": "truffles", 
   "groc 2":"some thing"
}

Where groc 1 and groc 2 are two of the key value pairs.其中 groc 1 和 groc 2 是两个键值对。 The names (groc 1) are not known at compile time and could be anything in any amount.名称(groc 1)在编译时是未知的,可以是任何数量的任何东西。 They need to be passed as parameters to another external system with those unknown fields as the name/key.它们需要作为参数传递给另一个外部系统,这些未知字段作为名称/键。

Trying to figure out how best to do this.试图弄清楚如何最好地做到这一点。 I've been fiddling with contract resolvers and converters but not getting anywhere..maybe something with expando objects and reflection?我一直在摆弄合同解析器和转换器,但没有得到任何地方..也许是expando对象和反射的东西? But seems like someone must have run into this before so maybe there is an easier way all my googling hasn't found yet.但似乎之前一定有人遇到过这个问题,所以也许我的谷歌搜索还没有找到一种更简单的方法。 Seems like it should be simple but I've been staring at it too long.似乎它应该很简单,但我已经盯着它太久了。 I can change the structure or type of the child object, but output needs to be like above.我可以更改子 object 的结构或类型,但 output 需要像上面那样。

Any suggestions?有什么建议么?

you can try this你可以试试这个

var newObj=JObject.Parse(json);
var customFields=(JArray) newObj["CustomFields"];
newObj.Properties().Where(p=> p.Name=="CustomFields").First().Remove();

foreach (JObject item in customFields)
    newObj.Add((string) item["key"],item["value"]);

json=newObj.ToString();

json json

{
  "part": 1,
  "quant": 2,
  "comments": "something",
  "groc 1": "truffles",
  "groc 2": "some thing"
}

but if you need c# classes, you have to create a custom class using a Dictionary as JsonExtensionData但如果您需要 c# 类,则必须使用 Dictionary as JsonExtensionData 创建自定义 class

Item newItem=newObj.ToObject<Item>();

public class Item
{
    public int part { get; set; }
    public int quant { get; set; }
    public string comments { get; set; }

    [JsonExtensionData]
    public IDictionary<string, object> CustomFields { get; set; }
}

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

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