序列化字典没有与Newtonsoft.Json属性名 [英] Serialize Dictionary without property name with Newtonsoft.Json

查看:426
本文介绍了序列化字典没有与Newtonsoft.Json属性名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用

var myResponse = new Response(myDictionary);
string response = JsonConvert.SerializeObject(myResponse);



其中,

where

internal class Response 
{
    public Response (Dictionary<string, string> myDict) 
    {
        MyDict = myDict;
    }

    public Dictionary<string, string> MyDict { get; private set; }
}



我收到:

I'm getting:

{
  "MyDict": 
  { 
     "key" : "value", 
     "key2" : "value2"
  }
}

我想要得到的是:

{
    "key" : "value", 
    "key2" : "value2"
}

`

有可能与Newtonsoft的以.json?

is that possible with Newtonsoft.Json?

推荐答案

您正在序列化整个对象。如果你只是想你指定的输出则只是序列化词典:

You're serializing the entire object. if you just want the output you specified then just serialize the dictionary:

string response = JsonConvert.SerializeObject(myResponse.MyDict);

这将输出:

{"key":"value","key2":"value2"}

这篇关于序列化字典没有与Newtonsoft.Json属性名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆