I have code that gets data from JSON:
dynamic myJSON = Newtonsoft.Json.JsonConvert.DeserializeObject(sourceString);
foreach (var item in myJSON["data"]["results"])
{ ... }
Now, I'd like to make this part myJSON["data"]["results"] for versatile, ideally by passing in a variable such as:
dynamic myJSON = Newtonsoft.Json.JsonConvert.DeserializeObject(sourceString);
var variableResults = ((Newtonsoft.Json.Linq.JArray) string.Format("myJSON[\"{0}\"][\"{1}\"]", myData, myResults);
foreach (var item in variableResults)
{ ... }
I've tried different conversions, and looked here, but no question comes close, and the conversions always comes out string, not a JArray. Any ideas?
You can use JObject to parse it:
var json = "{asd: {qwe: [1,2,3,4]}}";
var obj = JObject.Parse(json);
// just plug in your variables here
var myData = "asd";
var myResult = "qwe";
var path = $"{myData}.{myResult}";
foreach (var item in obj.SelectToken(path).ToObject<int[]>())
{
// ...
}
My solution ended up being:
// User would use a textbox with space separated values like "data results"
var parameterList = textBox1.Text.Trim().Replace(" ", ".");
var jsonObject = JObject.Parse(sourceString);
var jsonList = jsonObject.SelectToken(parameterList);
if (jsonList == null) { ... }
foreach (var item in jsonList)
{ ... }
Related
I am accessing the following Json output from a sports statistics API and want to get the specific value that rests in the away team ID for each game being played. (dates>games>teams>away>team:id). Json show here: https://statsapi.web.nhl.com/api/v1/schedule
I've been successful using jObject.Parse() for much of the rest of my project but this value is buried and my knowledge is limited on how to expand my nest to reach it. Any help would be greatly appreciated.
so far I am trying like so but getting errors stating I am accessing invalid key values.
public List<string> GetAwayTeamsPlayingToday()
{
var URL = new UriBuilder("https://statsapi.web.nhl.com/api/v1/schedule");
var client = new WebClient();
List<string> awayTeamsPlayingToday = new List<string>();
JObject ScheduleData = JObject.Parse(client.DownloadString(URL.ToString()));
string lplayerAwayTeamId = string.Empty;
var dates = ScheduleData["dates"] as JArray;
foreach (JObject date in dates)
{
var games = dates["games"] as JArray;
foreach (JObject game in games)
{
var teams = games["teams"] as JArray;
foreach (JObject team in teams)
{
var away = teams["away"] as JArray;
foreach (JObject tm in away)
{
var awayTeam = away["team"] as JObject;
lplayerAwayTeamId = awayTeam["id"].ToString();
awayTeamsPlayingToday.Add(lplayerAwayTeamId);
}
}
}
}
return awayTeamsPlayingToday;
}
You can do this
var URL = new UriBuilder("https://statsapi.web.nhl.com/api/v1/schedule");
var client = new WebClient();
List<string> awayTeamsPlayingToday = new List<string>();
JObject ScheduleData = JObject.Parse(client.DownloadString(URL.ToString()));
var data = JsonConvert.DeserializeObject<dynamic>(ScheduleData.ToString());
//this sample is for first date, first game
var awayTeamId = data.dates[0].games[0].teams.away.team.id;
//to get each game
foreach (var date in data.dates)
{
foreach (var game in date.games)
{
var id = game.teams.away.team.id;
//your logic
}
}
I have struggled to finish this task, please if anyone can give me a hint I would be so thankful.
My main task is to get data from database using (FOR JSON AUTO) which is working :)
select filed1, field2, field3 from table FOR JSON AUTO;
And then after connecting to Data base I use the StringBuilder() to build a Json Array of objects which is working :)
var jsonResult = new StringBuilder();
if(!r.HasRows)
{
jsonResult.Append("[]");
}
else
{
while(r.Read())
{
jsonResult.Append(r.GetValue(0).ToString());
}
// JArray array = JArray...
}
After that I am trying to change the value of filed1 for each object inside the Json Array
JArray array = JArray.Parse(jsonResult.ToString());
foreach (JObject obj in array.Children<JObject>())
{
foreach (JProperty singleProp in obj.Properties())
{
string name = singleProp.Name;
string value = singleProp.Value.ToString();
if(name.ToString() == "field1")
{
Int64 newID = 1234;
value = newID.ToString();
}
}
}
This is working but My BIG QUESTION is how can I get it changed inside the jsonResult?
You simply have to replace the value that you want to update. Since StringBuilder has a .Replace inbuilt method, you can implement that method.
`JArray arr = JArray.Parse(jsonResult.ToString());
foreach (JObject obj in arr.Children<JObject>())
{
foreach(JProperty singleProp in obj.Properties())
{
string name = singleProp.Name;
string value = singleProp.Value.ToString();
if (name.ToString().Equals("field1")) //good practice
{
Int64 newID = 1234;
jsonResult.Replace(value, newID.ToString());//replacing old value with new value and directly updates jsonResult
}
//not necesssary, explanation is given below
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonResult.ToString());
result = JsonSerializer.Serialize(jsonElement, options);
}
}`
And for better formatting, I used JsonSerializer so that your output will look like json object rather than whole string without any lines.
` var options = new JsonSerializerOptions()
{
WriteIndented = true
};
var result = ""
while loop{
jsonResult.Append(r.GetValue(0).ToString());
(Above code)
}
`
I am trying to parse JSON string in C# solution, but I can't get the internal/nested arrays which start with : ",[["bd felek",0],["bdm",0],["bd",0],["bdz",
["bd",[["bd felek",0],["bdm",0],["bd",0],["bdz",0,[131]],["bd fleke",0],["bd felek dfdf",0],["bdz dance practice",0,[3]],["bdz twice live",0,[131]],["bdo",0,[131]],["bd mawlaya",0]],{"a":"Uwt304b6at0ZtuU8mv8D5AyWS8wg6AQJQbYlPPS8knOVvcG","e":"1","j":"6l","k":1,"q":"ZQXxB0vG-GaPEF2RNib3gbVRXt0"}]
var jsonser = new JavaScriptSerializer();
var obj = jsonser.Deserialize<dynamic>(SourceCodeTxt.Text);
foreach (var x in obj)
{
// MessageBox.Show(x);
String strvalue = x["value"];
}
}
Your code should be looking at the second index (1) of the deserialized object:
foreach (var x in obj[1])
{
var value1 = x[0]; // bd felek
var value2 = x[1]; // 0
}
You want to use JSON.NET to better handle JSON. then you can simply do the following:
using Newtonsoft.Json.Linq;
...
JToken obj = JToken.Parse(/* Your JSON string goes in here */);
foreach (var x in obj[1])
{
var value1 = x[0]; // bd felek
var value2 = x[1]; // 0
...
}
With My code I can Generate Lots of Places name from a Wikipedia article. Suppose if I look for Flensburg wikipedia page it will give all the external page links of places as name. So at this moment all the places are shown on output as list form like
Maasbüll
Bov Municipality
Hürup
Hürup(Amt)
Kupfermühle
.........and so on...
Now what I want to do is, I want to store all these places paired with its city name. Suppose here Flensburg is the city name. So i want to store it as following way-
Flensburg;Maasbüll;Bov Municipality;Hürup;Hürup(Amt);Kupfermühle.... so on..
My code to generate list of all places are as follows-
using (var client = new HttpClient())
{
var response = client.GetAsync("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Flensburg&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = responseContent.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<RootObject>(responseString).query.geosearch.Select(a => a.title).ToList();
foreach (var item in obj)
{
Console.WriteLine(item);
}
}
}
I want to know how can I store my data like I mentioned.
using System.Collections.Generic;
Code:
Dictionary<string, string> cities = new Dictionary<string, string>();
string query = "Flensburg";
using (var client = new HttpClient())
{
var response = client.GetAsync("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=" + WebUtility.UrlEncode(query) + "&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = responseContent.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<RootObject>(responseString).query.geosearch.Select(a => a.title).ToList();
List<string> places = new List<string>();
foreach (var item in obj)
{
places.Add(item);
}
cities[query] = string.Join(";", places);
Console.WriteLine(query + ":" + cities[query]);
var output = query + ";" + cities[query];
File.WriteAllText(#"C:\C# Visual Studio\City.txt", output);
}
}
As per your own tag, A Dictionary will do exactly what you want.
Dictionary<string, Object> cities = new Dictionary<string, Object>();
cities.Add(name, item);
Do this -
var output = String.Join(";", obj );
Dictionary<cityname,List<associated places>> d = new Dictionary<cityname,List<associated places>>();
key will be the city name that you search and value is a list which contains all the associated places
Add multiple places as values in a list with a single key of a dictionary.
I have below json in string as parameter to a WebMethod.
How can I deserialize in such a way that value comes in Key value pair.
Json String Parameter:
["Ref No,0","Date,0","Amt,0","Sender Name,0","Sender Add,0","Beneficiary Name,0","Beneficiary Add,0","Phone,0","Secret Code,0","Secret Ans,0","Preferred Id,0"]
WebMethod:
[System.Web.Services.WebMethod]
public static string SaveMappings(string mappingData)
{
//string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//object obj;
//var data = serializer.Deserialize(mappingData,);
var data = mappingData.ToArray();
if (data != null)
{
}
var d2 = mappingData.Split(',');
if (d2!=null)
{
}
return mappingData;
}
If you need to work with JSON data then use Newtonsoft.JSON library.
Convert the object to an array of strings and then split every line.
With this approach you can be sure that the given string is actually an JSON array and it is correct.
var str = "[\"Ref No,0\",\"Date,0\",\"Amt,0\",\"Sender Name,0\",\"Sender Add,0\",\"Beneficiary Name,0\",\"Beneficiary Add,0\",\"Phone,0\",\"Secret Code,0\",\"Secret Ans,0\",\"Preferred Id,0\"]";
string[] objs = JsonConvert.DeserializeObject<string[]>(str);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var obj in objs)
{
var keyValue = obj.Split(',');
dic.Add(keyValue[0], keyValue[1]);
}
foreach (var record in dic)
{
Console.WriteLine("{0} => {1}", record.Key, record.Value);
}
Or this one using LINQ. It looks better and it can be written faster. However, it is less optimal (two calls of Split instead of one).
public Dictionary<string, string> FromJsonArray(string jsonArray)
{
return JsonConvert.DeserializeObject<string[]>(jsonArray)
.ToDictionary(obj => obj.Split(',')[0], obj => obj.Split(',')[1]);
}
// ...
var str = "[\"Ref No,0\",\"Date,0\",\"Amt,0\",\"Sender Name,0\",\"Sender Add,0\",\"Beneficiary Name,0\",\"Beneficiary Add,0\",\"Phone,0\",\"Secret Code,0\",\"Secret Ans,0\",\"Preferred Id,0\"]";
foreach (var record in FromJsonArray(str))
{
Console.WriteLine("{0} => {1}", record.Key, record.Value);
}
why don't you just change every ',' in the string array to ':' then pass it to the method, from what you wrote in the question, this should work