Remove property from Json array - c#

I get the content from a api response like this:
var response = await httpClient.GetAsync(new Uri("http://localhost:1337/" + route));
var responseContent = await response.Content.ReadAsStringAsync();
responseContent looks like this:
[{"caption":"Type Value List","name":"ReportsTypeValueList","visible":true,"enabled":true,"controlName":null,"elements":[{"caption":"Detail","name":"Detail","visible":true,"enabled":true,....
I parsed it into a Json array.
One of the json objects inside the json array has a property called defaultValue
with timestamp as it's value looking like this for example:
"defaultValue": "2019-07-18T11:29:13.623245Z"
How can I remove this property from the Json array?

Assuming you are using a Json.Net lib then you can do
JObject myJsonResponse = JObject.Parse(responseContent);
myJsonResponse.Property("defaultValue").Remove();

You can use this.
array.Children<JObject>().FirstOrDefault(x => x.Value<string>
("defaultValue") == "2019-07-18T11:29:13.623245Z").
Property("defaultValue").Remove();

Related

Add property to each object in JSON C#

I have a JSON body which looks like this(an array of objects):
[
{
"registered": "2016-02-03T07:55:29",
"color": "red",
},
{
"registered": "2016-02-03T17:04:03",
"color": "blue",
}
]
This body is contained in a variable(requestBody) I create based on a HTTP Request, it's called req:
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
What I want to do is add a unique identifier to each one of the objects in my JSON array. How could I go about achieving this?
Currently I am deserializing the JSON, adding some string(x) to it and then serializing it again:
dynamic d = JsonConvert.DeserializeObject(requestBody);
d.uniqueId = "x";
string newBody = JsonConvert.SerializeObject(d);
I was to add a uniqueId to each one of the objects in my JSON array of objects. How could I achieve this?
You can use JArray from LINQ to JSON API to parse, iterate children of JObject type and modify them:
var json = ...; // your json string
var jArray = JArray.Parse(json);
foreach (var jObject in jArray.Children<JObject>())
{
jObject.Add("id", new JValue("x"));
}
var modified = JsonConvert.SerializeObject(jArray);

insert data into existing JSON Array in C#

I need to add some more data into existing JSON
eg:
{
"OrderId":"abc",
"products":["a","b","c","etc"]
}
how to add more into products
The approach would be similar to used in answer to your previous question, but you will need to convert element to JArray:
var x = #"{
'OrderId':'abc',
'products':['a','b','c','etc']
}";
var jObj = JObject.Parse(x);
((JArray)jObj["products"]).Add("new");
Try this:
var jObject = JObject.Parse(json);
var jArray = jObject["products"] as JArray;
jArray?.Add("new_product");

Newtonsoft.Json, How to code generic selection

Further on with Newtonsoft.Json, Path returned multiple tokens,
For this code:
JObject o = JObject.Parse(jsStr);
IEnumerable<JToken> selEnum = o.SelectTokens(theFilter);
where the jsStr is the content of https://api.github.com/search/repositories?q=Newtonsoft.Json&sort=stars&order=desc, and theFilter can be any valid JPATH query string (e.g., ".items" or ".items[*].owner").
How to return the selected as a valid json string?
It sounds like you just need Json.SerializeObject:
var o = JObject.Parse(jsStr);
var selEnum = o.SelectTokens(theFilter);
var newJson = JsonConvert.SerializeObject(selEnum);
This will give you JSON representing an array of all of the owner values from the original JSON.

Removing an element from a JSON response

I have a JSON string from which I want to be able to delete some data.
Below is the JSON response:
{
"ResponseType": "VirtualBill",
"Response": {
"BillHeader": {
"BillId": "7134",
"DocumentId": "MN003_0522060",
"ConversionValue": "1.0000",
"BillType": "Vndr-Actual",
"AccountDescription": "0522060MMMDDYY",
"AccountLastChangeDate": "06/07/2016"
}
},
"Error": null
}
From above JSON response I want to able remove the
"ResponseType": "VirtualBill", part such that it looks like this:
{
"Response": {
"BillHeader": {
"BillId": "7134",
"DocumentId": "MN003_0522060",
"ConversionValue": "1.0000",
"BillType": "Vndr-Actual",
"AccountDescription": "0522060MMMDDYY",
"AccountLastChangeDate": "06/07/2016"
}
},
"Error": null
}
Is there an easy way to do this in C#?
Using Json.Net, you can remove the unwanted property like this:
JObject jo = JObject.Parse(json);
jo.Property("ResponseType").Remove();
json = jo.ToString();
Fiddle: https://dotnetfiddle.net/BgMQAE
If the property you want to remove is nested inside another object, then you just need to navigate to that object using SelectToken and then Remove the unwanted property from there.
For example, let's say that you wanted to remove the ConversionValue property, which is nested inside BillHeader, which is itself nested inside Response. You can do it like this:
JObject jo = JObject.Parse(json);
JObject header = (JObject)jo.SelectToken("Response.BillHeader");
header.Property("ConversionValue").Remove();
json = jo.ToString();
Fiddle: https://dotnetfiddle.net/hTlbrt
Convert it to a JsonObject, remove the key, and convert it back to string.
Sample sample= new Sample();
var properties=sample.GetType().GetProperties().Where(x=>x.Name!="ResponseType");
var response = new Dictionary<string,object>() ;
foreach(var prop in properties)
{
var propname = prop.Name;
response[propname] = prop.GetValue(sample); ;
}
var response= Newtonsoft.Json.JsonConvert.SerializeObject(response);

Take the information from json

I'm trying to parse "VID" from this json data
{"response":[2,{"vid":165971367},{"vid":165971350}]}.
But it don't want to parse it. I think there is problem with "2" in json data. How to eliminate this figure?
Here is my code:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("some json data");
string googleSearchText = await response.Content.ReadAsStringAsync();
JObject googleSearch = JObject.Parse(googleSearchText);
IList<JToken> results = googleSearch["response"].Children().ToList();
IList<SearchResult> searchResults = new List<SearchResult>();
If you were usng Json.Net and loaded that json into a JObject then you have a property called "response" so:
myJson["response"]
which is a JArray with 3 elements, so skip the first element.
.Skip(1)
Then you have IEnumerable and want property "vid", so something like:
var myVids = (from vids in myJObject["response"].Skip(1)
where vids["vid"] != null
select vids["vid"])
/* JSON
{"response":
[2,
{"vid":165971367},
{"vid":165971350}
]
}
*/
Of course, this is just the concept and you would need to adjust for real life.
You can skip the first item by using Skip method:
IList<JToken> results = googleSearch["response"].Skip(1).ToList();

Categories