Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

json.net - How to remove parent element from json in c#

How to covert the below json

{"data":{"id":12,"name":"jeremy","email":"[email protected]"}}

to

{"id":12,"name":"jeremy","email":"[email protected]"}

I want to remove the "data" element from json.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With json.net it's fairly straightforward

var input = "{"data":{"id":12,"name":"jeremy","email":"[email protected]"}}";
var result = JObject.Parse(input)["data"].ToString(Formatting.None);
Console.WriteLine(result);

Note : Formatting.None is only to preserve the formatting you had in your original example

Or Text.Json

var result = JsonDocument.Parse(input).RootElement.GetProperty("data").ToString();

Output

{"id":12,"name":"jeremy","email":"[email protected]"}

Additional Resources

JObject.Parse Method (String)

Load a JObject from a string that contains JSON.

JObject.Item Property (String)

Gets or sets the JToken with the specified property name.

JToken.ToString Method (Formatting,JsonConverter[])

Returns the JSON for this token using the given formatting and converters.

Formatting Enumeration

None 0 No special formatting is applied.


Text.Json

JsonDocument.Parse Method

Provides a mechanism for examining the structural content of a JSON value without automatically instantiating data values.

JsonDocument.RootElement Property

Gets the root element of this JSON document

JsonElement.GetProperty Method

Gets a JsonElement representing the value of a required property identified by propertyName.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...