This question already has answers here:
Find an item in a list by LINQ
(14 answers)
Closed 4 years ago.
I have a json list and I have a type named post. I want to use it for search.
I want to get a list or one object with a query. Is that possible ?
Example part of json
{
"Post": [
{
"id":"22",
"text":"Dream Big",
"img":"a2ca3cf9-664e-4d92-80f1-df20e971b7c0.jpg",
"catid":"12",
"meta_title":"Dream Big Design",
"content":"some text",
"user_id":"5556",
}
{
"id":"24",
"text":"Handmade Resin",
"img":"423233-971b7c0.jpg",
"catid":"7",
"meta_title":"Handmade Resin",
"content":"some text",
"user_id":"1256",
}
]
}
I want to select id = 23 or name like 'handmade'.
I tried with this code but it did not work
string json = System.IO.File.ReadAllText(path + "output.json");
var serializer = new JavaScriptSerializer();
Post post = JsonConvert.DeserializeObject<Post>(json);
you can use JObject in the C# that can parse the Json object and then you can fire your Select query.
JObject jObject = JObject.Parse(your Json object in string);
Related
This question already has answers here:
Deserialize JSON with C#
(10 answers)
Closed 2 years ago.
Not that much experience using json, I have read many topics on this but it seems like no one's got the same json structure that I'm working with so i cant seem to get the following items deserialized, basically i will be populating a listbox with all bucketName in the list as shown below, the json gets returned from a web request.
This currently holds all the json data:
var responseString = new StreamReader(responseList.GetResponseStream()).ReadToEnd();
And this is the content it holds:
{
"buckets":
[
{
"accountId": "someweirdid",
"bucketId": "4a48fe8875c6214145260818",
"bucketInfo": {},
"bucketName" : "Kitten-Videos",
"bucketType": "allPrivate",
"lifecycleRules": []
},
{
"accountId": "uuhhmthisisarandomid",
"bucketId" : "5b232e8875c6214145260818",
"bucketInfo": {},
"bucketName": "Puppy-Videos",
"bucketType": "allPublic",
"lifecycleRules": []
},
{
"accountId": "ahhhanotherid",
"bucketId": "87ba238875c6214145260818",
"bucketInfo": {},
"bucketName": "Vacation-Pictures",
"bucketType" : "allPrivate",
"lifecycleRules": []
}
]
}
I need the bucketName item to be populated in a listbox, please any help, thanks.
Try converting json object to C# and create a list which can be used to populate listbox
using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);
This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 2 years ago.
I have method where I call another API. From
var activeCustomers = await response.Content.ReadAsStringAsync();
I get string which contains [timestamp, value] objects:
{"values":[[1298937600000,1],[1459468800000,16],[1462060800000,527],[1464739200000,173],[1467331200000,132],[1470009600000,166],[1472688000000,151],[1475280000000,172],[1477958400000,139],[1480550400000,129],[1483228800000,116],[1485907200000,133],[1488326400000,180],[1491004800000,227],[1493596800000,281],[1496275200000,263],[1498867200000,230],[1501545600000,326],[1504224000000,403],[1506816000000,442],[1509494400000,1019],[1512086400000,650],[1514764800000,708],[1564617600000,2614],[1567296000000,2527],[1569888000000,3144],[1572566400000,3075],[1575158400000,2541],[1577836800000,2246],[1580515200000,2456],[1583020800000,885]]}
I want to parse these values into key value pairs, but I am not sure what's the most optimal way for that.
I tried removing beginning and ending of string and cast it as object but it stays as one big string inside the ienumerable:
int index = activeCustomers.IndexOf(":");
if (index > 0)
activeCustomers = activeCustomers.Substring(index + 1);
activeCustomers = activeCustomers.Remove(activeCustomers.Length - 1);
var results = ((IEnumerable) activeCustomers).Cast<object>();
I also tried making regex for that but I am not very comfortable with that.
This just a JSON with array of arrays, which can be easily deserialized using Json.NET
var result = JsonConvert.DeserializeObject<Root>(activeCustomers);
or System.Text.Json
var result = JsonSerializer.Deserialize<Root>(activeCustomers);
Where Root is
public class Root
{
public long[][] values { get; set; }
}
Then you can map the values property to any desired structure using Select method
var pairs = result.values.Select(v => new { timestamp = v[0], value = v[1] }).ToList();
This question already has answers here:
Get values from dynamic JSON properties C#
(2 answers)
Closed 2 years ago.
I'm sorry if I'm asking a trivial question but I'm stuck so I'm asking for your help.
I currently have a dynamic json that I receive, and I would like that according to the value of the phone the corresponding field is retrieved.
For exemple in my foreach(var item in jsonResult),
if item["Phone"].Value = "PSTN"( or "UIFN", "TS", "RS", "TF" ) then I would like to retrieve the json field which corresponds with its value, in this case it would be "PSTN".
If anyone has an idea how I can make this happen.
Thank you in advance for your answers and your help.
I believe this post can help you.
Try this code:
JObject jObject = JObject.Parse(jsonResult);
var result = (JObject)jObject["put here your top node level"];
foreach(JProperty prop in result.Properties())
{
if (prop.Name == item["Phone"].Value)
{
var values = jObject["put here your top node level"][prop.Name].Values<string>(item["Phone"].Value);
// do something
}
}
You could do it like this. thang.json is a file with json you provided.
var json = File.ReadAllText("thang.json");
var deserialized = JsonConvert.DeserializeObject<dynamic>(json);
if (new[] {"PSTN", "UIFN", "TS", "RS", "TF"}.Contains((string) deserialized.Phone))
{
Console.WriteLine(deserialized[(string)deserialized.Phone]);
}
This question already has answers here:
How to Convert JSON object to Custom C# object?
(13 answers)
Closed 5 years ago.
i want to get the data from my returning api jsonstring.
my result string looks like this
[
{"Id":12,"name":"testname","type":"testtype"}
{"Id":12,"name":"testname","type":"testtype"}
{"Id":12,"name":"testname","type":"testtype"}
]
how can i extract this data to c# objects
i can only do it ones
var obj = JObject.Parse(result);
var ID = (int)obj["Id"];
var Name = (String)obj["name"];
var type = (String)obj["type"];
User u = new User(ID,Name,Type);
Your string is not valid JSON, so making it valid JSON is the first step to process it quickly. The easiest thing to do is to make it a JSON array:
string jsonArray = "["
+ string.Join(", ", json.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
+ "]";
From then on it is straightforward (see my related answer: Easiest way to parse JSON response):
var result = JsonConvert.DeserializeObject<User[]>(jsonArray);
Another option is to split the lines yourself, and parse and add the items to a list manually.
Result is an array of JSON.. so loop and parse
list<User> userList = new list<User>();
for(int i=0 ; i <result.length; i++)
{
var obj = JObject.Parse(result[i]);
var ID = (int)obj["Id"];
var Name = (String)obj["name"];
var type = (String)obj["type"];
User u = new User(ID,Name,Type); //create User
userList.add(u); //Add to list
}
This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Closed 8 years ago.
I am fairly new to C# / JSON and am working on a pet project to show summoner/game information from league of legends.
I am trying to get the summoner id for the requested summoner name.
Here is the JSON returned:
{"twopeas": {
"id": 42111241,
"name": "Twopeas",
"profileIconId": 549,
"revisionDate": 1404482602000,
"summonerLevel": 30
}}
Here is my summoner class:
public class Summoner
{
[JsonProperty(PropertyName = "id")]
public string ID { get; set; }
}
Here is the rest:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
var summonerInfo = JsonConvert.DeserializeObject<Summoner>(result);
MessageBox.Show(summonerInfo.ID);
summonerInfo.ID is null and I don't know why.
I'm sure there is something glaringly obvious that I am missing, but I'm at a loss I can't for the life of me figure it out.
Your ID is null because your JSON doesn't match the class you're deserializing into. In the JSON, the id property is not at the top level: it is contained within an object which is the value of a top-level property called twopeas (presumably representing the summoner name). Since this property name can vary depending on your query, you should deserialize into a Dictionary<string, Summoner> like this:
var summoners =
JsonConvert.DeserializeObject<Dictionary<string, Summoner>>(result);
MessageBox.Show(summoners.Values.First().ID);