{"data": {"day2": {"mId": "9ilrMdX15S", "votes": "2,893"},"day3": {"mId": "9ilert415S","votes": "2,343"}}}
How can i retrieve the data from a json data as such (i.e the data in "day2", or "day3") i followed the answers here > Appending json data to listview c# by Brain Rogers but the answer only work for json object not for nested json.
Here's an example of how to navigate it:
foreach (JProperty day in JObject.Parse(json)["data"])
{
string name = day.Name;
string id = day.Value.Value<string>("mId");
string votes = day.Value.Value<string>("votes");
}
Thanks for all the response, i was able to solve the task using the SimpleJSON library by Bunny83 GitHub - Bunny83/SimpleJSON: A simple JSON parser in C#
JSONNode data = JSON.Parse(//jsonData or Url//);
string mId = data["data"]["day2"]["mId"].Value;
string votes = data["data"]["day2"]["votes"].Value;
Related
I am absolutely new in Json stuff, following is one of my returned JSON string from one of the Internal REST API Call:
{
"odata.metadata":"https://ABC.XYZ.com/ERP10TESTNSSO/api/v1/Erp.BO.ABCCodeSvc/$metadata#Epicor.RestApi.ABCCodes/#Element",
"Company":"93100",
"ABCCode1":"A",
"CountFreq":1,
"ExcludeFromCC":false,
"StockValPcnt":"0",
"PcntTolerance":"0.00",
"CalcPcnt":false,
"CalcQty":false,
"CalcValue":false,
"QtyTolerance":"0",
"ValueTolerance":"0",
"ShipToCustNum":0,
"SysRevID":"6066188743",
"SysRowID":"5b7e2172-7f7a-445e-983d-f230e050153d",
"BitFlag":0,
"RowMod":""
}
Please let me know, how may I convert it into C# Data Table?
I tried following code (posted by another kind techie)
dynamic jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonContent);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(Convert.ToString(jsonObject.Value));
But this code is throwing error at jsonObject.Value.
Please help me to fix it ...
Try this:
string json = "{\"odata.metadata\":\"https://ABC.XYZ.com/ERP10TESTNSSO/api/v1/Erp.BO.ABCCodeSvc/$metadata#Epicor.RestApi.ABCCodes/#Element\",\"Company\":\"93100\",\"ABCCode1\":\"A\",\"CountFreq\":1,\"ExcludeFromCC\":false,\"StockValPcnt\":\"0\",\"PcntTolerance\":\"0.00\",\"CalcPcnt\":false,\"CalcQty\":false,\"CalcValue\":false,\"QtyTolerance\":\"0\",\"ValueTolerance\":\"0\",\"ShipToCustNum\":0,\"SysRevID\":\"6066188743\",\"SysRowID\":\"5b7e2172-7f7a-445e-983d-f230e050153d\",\"BitFlag\":0,\"RowMod\":\"\"}";
json = $"[{json}]";
DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);
Add [ ] in your json string.
New to C#. I have a URL https://osu.ppy.sh/beatmapsets/781509#osu/1642274
with multiple json objects but I want to retrieve only the object with id="json-beatmapset" from this URL. This is my current piece of code:
string url = #"https://osu.ppy.sh/beatmapsets/781509#osu/1642274";
var code = new WebClient().DownloadString(url);
Console.WriteLine(code);
And I want to be able to extract information (for example the title) from this one json object using this:
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(json);
string title = dobj["title"].ToString();
Console.WriteLine(title);
where json is the json object, which should print
Black Rover (TV Size)
How do I get the json object from this url?
As per my comment, you can use regular expressions to parse string data.
var json = Regex.Match(code, "<script id=\"json-beatmapset\".*?>(.*?)<\\/script>", RegexOptions.Singleline).Groups[1].Value;
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(json);
string title = dobj["title"].ToString();
Console.WriteLine(title);
I created an ASP.NET Application, where I have to parse a csv file with a json structure.
The csv file itself is structured like:
{"Instance":"abc","Date":"2019-06-03T00:00:02.056Z","Identification":"someFunction","Type":"DurationInMs","Value":"5","iserror":"False""}
I get the jsonCsvData as a string and tried to parse it. Then I want to save some of the elements of this json object into a db.
public IActionResult ReadJsonCsvData(string jsonCsvData)
{
Console.WriteLine("ReadJsonCsvData");
ChartData chartData = new ChartData();
var lines = jsonCsvData.Split("\n");
foreach (var line in lines)
{
var values = JObject.Parse(line);
var first = string.Concat(values["Instance"]); //Output for first: ""
}
}
The problem now is, that the variable first is an empty string. The result should be (like in the json structure example above) "abc".
Thank you in advance!
I don't know if it will help but here is my solution (remove one of " at the end of your Json).
I use the "Jobject" to parse Json as I want. Import this two reference.
using Newtonsoft.Json.Linq;
using Newtonsoft;
Then you have to create your JObject :
JObject o = JObject.Parse(myJsonString);
Then to retrieve specifics data, you just have to search in your object just like you do with a dictionary with key :
instanceFromJson = o["Instance"].ToString;
dateFromJson = o["Date"].ToString;
If you have a table in your "instance" json object you can retrieve all data from this list just like that :
foreach (var item in o["Instance"]["tabFromInstanceObject"])
{
MyList.Add(item);
}
I'm trying to automate the addition of new objects to an existing JSON file. I looked all around the web but only found adding data and stuff but not a whole object. This is how the file that I want to edit looks:
[
{"id":"123","name":"carl"}
]
and I want to go to
[
{"id":"123","name":"carl"},
{"id":"1234","name":"carl2"}
]
Thank you for all your answers but I don't think everyone completely understands what i mean I have tried some of the answers but then I get this:
[
"{\"id\":\"123\",\"name\":\"carl\"}"
]"{\"id\":\"1234\",\"name\":\"carl2\"}"
and I want everything in between the [].
If you use json.NET you can simply deserialize and serialize the json.
var list = JsonConvert.DeserializeObject<List<Person>>(myJsonString);
list.Add(new Person(1234,"carl2");
var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented);
Using Json.Net
//load from file
var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
var array = JArray.Parse(initialJson);
var itemToAdd = new JObject();
itemToAdd["id"] = 1234;
itemToAdd["name"] = "carl2";
array.Add(itemToAdd);
var jsonToOutput = JsonConvert.SerializeObject(array, Formatting.Indented);
//save to file here
Using this method doesn't require strongly typed objects
You could replace this bit:
//load from file
var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
With
var initialJson = File.ReadAllText(#"c:\myjson.json")
To load the json from a text file
A better performing solution than serializing/deserializing what may be a large file would be to open a FileStream, seek 1 character before the end, then serialize and write your new object into the array, then write a closing bracket. See this question C# How to delete last 2 characters from text file and write into the same line at the end my text?, I'll copy the code here - you already know how to serialize your object and encode it into bytes.
using(var fs = new FileStream("file.json")) {
fs.Seek(-1,SeekOrigin.End);
fs.Write(mySerializedJSONObjAsBytes,0,mySerializedJSONObjAsBytes.Length); // include a leading comma character if required
fs.Write(squareBracketByte, 0, 1);
fs.SetLength(fs.Position); //Only needed if new content may be smaller than old
}
Sorry haven't tested any of that, it's off the top of my head. Pro-tip: wrap FileStream in a StreamWriter so can write strings directly.
You could create a method:
public string AddObjectsToJson<T>(string json, List<T> objects)
{
List<T> list = JsonConvert.DeserializeObject<List<T>>(json);
list.AddRange(objects);
return JsonConvert.SerializeObject(list);
}
Then use it like this:
string baseJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
List<Person> personsToAdd = new List<Person>() { new Person(1234,"carl2") };
string updatedJson = AddObjectsToJson(baseJson, personsToAdd);
this would be a sample for you:
var list = JsonConvert.DeserializeObject<List<Example>>(json);
Example example = new Example();
example.name = "Product2";
example.id="1";
list.Add(example);
string output = JsonConvert.SerializeObject(list);
public class Example
{
public string id {get;set;}
public string name { get; set; }
}
I have been looking for a solution to this exact question for a week now. I finally figured out how to append it to the existing json array and not add it as a solo object after the array. Make sure you are using WriteAllText and not AppendAllText. Here is what I did:
JArray array = JsonConvert.DeserializeObject<JArray (jsonFile);
JObject obj = new JObject();
obj.Add("ID", "123");
obj.Add("Name", "Brian");
array.Add(obj);
var jsonToOutput = JsonConvert.SerializeObject(array, Formatting.Indented);
File.WriteAllText("fileName.json", jsonToOutput);
I'm getting a feed json from YouTube. I can get the "entry" element and the with:
JObject json = JObject.Parse(response);
foreach (var entry in json["feed"]["entry"]) {
var title = entry["title"];
}
But how do I get the Value for 'title'? entry["title].ToString() gives me both key and value as a string...
Please try to include the JSON you want to parse in your question.
That being said, going from the feed shown here, which is linked to from the Developer's Guide: JSON / JavaScript, you should do:
foreach (var entry in json["feed"]["entry"])
{
var title = (string)entry.SelectToken("title.$t");
}