I have a JObject item that looks like this:
{
"part":
{
"values": ["engine","body","door"]
"isDelivered": "true"
},
{
"manufacturer":
{
"values": ["Mercedes"]
"isDelivered": "false"
}
}
How can I get the values as a single string in C#?
The simplest way to get a value from LINQ to JSON is to use the Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want. JObject/JArray can also be queried using LINQ.
To check whether a property exists on a JObject , you can use the square bracket syntax and see whether the result is null or not. If the property exists, a JToken will be always be returned (even if it has the value null in the JSON).
The JToken hierarchy looks like this: JToken - abstract base class JContainer - abstract base class of JTokens that can contain other JTokens JArray - represents a JSON array (contains an ordered list of JTokens) JObject - represents a JSON object (contains a collection of JProperties) JProperty - represents a JSON ...
JObject. It represents a JSON Object. It helps to parse JSON data and apply querying (LINQ) to filter out required data. It is presented in Newtonsoft. Json.
First create JObject from your string
String json = "{\"part\":{ \"values\": [\"engine\",\"body\",\"door\"], \"isDelivered\": \"true\"},\"manufacturer\":{\"values\": [\"Mercedes\"],\"isDelivered\": \"false\"}}";
JObject jObject = JObject.Parse(json);
Then get values array (from part for example as)
JArray jArray= (JArray)jObject["part"]["values"];
Convert JArray of String to string array
string[] valuesArray = jArray.ToObject<string[]>();
Join your string array & create a singe string
String values = string.Join(",",valuesArray);
Full code here ..
String json = "{\"part\":{ \"values\": [\"engine\",\"body\",\"door\"], \"isDelivered\": \"true\"},\"manufacturer\":{\"values\": [\"Mercedes\"],\"isDelivered\": \"false\"}}";
JObject jObject = JObject.Parse(json);
JArray jArray= (JArray)jObject["part"]["values"];
string[] valuesArray = jArray.ToObject<string[]>();
String values = string.Join(",",valuesArray);
Console.WriteLine(values);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With