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();
Related
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);
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");
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();
I am trying to return a JSON result from a REST API that includes a JsonObject as an element.
var aJsonObject = new JObject();
aJsonObject.Add("somefield", "somevalue" );
aJsonObject.Add("someotherfield", 1995);
return Json( new { status = "success", result = aJsonObject } );
The client receives an empty nested arrays:
{"status":"success","result":[[[]],[[]]]}
My work around, which I don't love, is to serialize the JsonObject, thus sending it as a string and then having the client parse it. It works, but it's a bit ugly.
Is this a bug or am I doing it wrong?
NOTE: 8/3/18 I edited the variable declaration to correct a typo - it was jsonObject and should have been aJsonObject
JObject is already json-formatted. Main purpose of JsonResult is to serialize an object to json. What you are trying to do is (I guess):
dynamic resultObject = new ExpandoObject();
resultObject.somefield = "somevalue";
resultObject.someotherfield = 1995;
return Json( new { status = "success", result = resultObject } );
If you want to build the Json string yourself and return it to the client you can use Content:
return new Content(yourjsonstring, "application/json");
And if you want to keep using JObject, this works (and then return the JSON as #ozum.e describes):
var jObject = new JObject();
jObject.Add("someField", "someValue");
jObject.Add("otherField", 1995);
var newObj = new { status = "success", result = jObject };
var returnThis = JsonConvert.SerializeObject(newObj);
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);