C# 在json中组合两个不同的对象

C# 在json中组合两个不同的对象,c#,json,C#,Json,下面是我的C#代码,它正在生成一些json输出:- var collection = new HeaderElements{ messageid = "hdhd", source = "sid", }; dynamic collectionWrapper = new{ Header = collection, Elements = new{ timestamp = "lk", value = "123" } }; str

下面是我的C#代码,它正在生成一些json输出:-

var collection = new HeaderElements{
    messageid = "hdhd",
    source = "sid",
};

dynamic collectionWrapper = new{
    Header = collection,
    Elements = new{
        timestamp = "lk",
        value = "123"
    }
};

string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(collectionWrapper);
Console.WriteLine(jsonString);
Console.ReadKey();
下面给出了所使用的类:-

public class HeaderElements{
    public string messageid { get; set; }
    public string source { get; set; }
}

public class Elements{
    public string timestamp { get; set; }
    public string value { get; set; }
}
我得到以下输出:-

"{\"Header\":{\"messageid\":\"hdhd\",\"source\":\"sid\"},\"Elements\":{\"timestamp\":\"lk\",\"value\":\"123\"}}"
但我希望我的输出采用以下格式:-

"{\"Header\":{\"messageid\":\"hdhd\",\"source\":\"sid\"},\"timestamp\":\"lk\",\"value\":\"123\"}"

我是json编程新手,我没有办法解决这个问题。

不要将时间戳和值放入元素变量中。将它们直接放入包装器中,如下所示:

dynamic collectionWrapper = new
{
    Header = collection,
    timestamp = "lk",
    value = "123"
};
这将提供您想要的输出:

{"Header":{"messageid":"hdhd","source":"sid"},"timestamp":"lk","value":"123"}

您需要的JSON不是有效的JSON。@FaizanRabbani,我确信\是一个调试器副本,插入真正的字符串作为分层和结尾”。删除这些,您就有了有效的JSON(RFC 4627)Yes@DragandDrop I removed/但仍然留有空格,这就是我出错的原因。JSON是正确的,我的错误:
{“Header”:{“messageid”:“hdhdhdhd”source:“sid”},“timestamp:“lk”,“value:“123”}
并请使用类来表示json对象。没有任何成本。这样,当您对如何使类表示json有疑问时,您可以创建use或Visual Studio Paste special(将json粘贴为类)。这样您就永远不会忘记格式化json。