I have a simple serialized json array
string json = "[{\"id\":100,\"UserId\":99},{\"id\":101,\"UserId\":98}]";
var data = (List<Model>)Newtonsoft.Json.JsonConvert.DeserializeObject(json , typeof(List<Model>));
my model to deserialize:
public class Model
{
public int? id { get; set; }
public int? UserId { get; set; }
}
What is the best way to retrieve data from each Index[?] and print it to Console ?
You can do a foreach loop:
foreach(var item in data) {
Console.WriteLine(item.UserId);
}
string json = "[{\"id\":100,\"UserId\":99},{\"id\":101,\"UserId\":98}]";
var objects = JArray.Parse(json);
var firstIndexValue = objects[0];
Console.WriteLine(firstIndexValue);
foreach (var index in objects)
{
Console.WriteLine(index);
}
for (int index = 0; index < objects.Count; index++)
{
Console.WriteLine(objects[index]);
}
Related
I have this JSON string called assignee:
{
"id": 15247055788906,
"gid": "15247055788906",
"name": "Bo Sundahl",
"resource_type": "user"
}
I want to get the "name" element and its value if it's not null. I have tried
var jobject = JsonConvert.DeserializeObject<JObject>(assignee);
And
var jo = JObject.Parse(assignee);
I tried looping through it but I just get null exception or empty output even though if I just print the assignee variable itself its filled with data.
My loop is like:
foreach (var result in jobject["name"])
{
Debug.WriteLine(result);
}
The simplest and best way is to deserialise to a C# class, for example:
public class Data
{
public long Id { get; set; }
public string Name { get; set; }
//etc..
}
And deserialise like this
var data = JsonConvert.DeserializeObject<Data>(json);
var name = data.Name;
To get name use this
string name = jobject["name"];
Using ["name"] returns a JToken, it is null if the property doesn't exist
JToken token = jo["name"];
Debug.WriteLine(token?.ToString() ?? "<default value>");
If you don't know properties beforehand, you can loop through JObject properties and get name value pairs as following:
var jsonObject = JObject.Parse(str);
foreach (var item in jsonObject)
{
var name = item.Key;
JToken token = item.Value;
if (token is JValue)
{
var value = token.Value<string>();
}
}
Here is how it should work:
class Data
{
public long? Id { get; set; }
public string Gid { get; set; }
public string Name { get; set; }
public string Resource_Type { get; set; }
}
class Program
{
static void Main(string[] args)
{
string assignee = "{\"id\": 15247055788906, \"gid\": \"15247055788906\", \"name\": \"Bo Sundahl\", \"resource_type\": \"user\"}";
Data data = JsonConvert.DeserializeObject<Data>(assignee);
Console.WriteLine(data.Id);
Console.WriteLine(data.Gid);
Console.WriteLine(data.Name);
Console.WriteLine(data.Resource_Type);
Console.ReadLine();
}
}
I'm trying to find out the index of a string in an array within a JObject object. For example, you could give frc610 and it would return 0.
// Get rankings JSON file from thebluealliance.com
string TBArankings = #"https://www.thebluealliance.com/api/v2/district/ont/2017/rankings?X-TBA-App-Id=frc2706:ONT-ranking-system:v01";
var rankings = new WebClient().DownloadString(TBArankings);
string usableTeamNumber = "frc" + teamNumberString;
string team_key = "";
int rank = 0;
dynamic arr = JsonConvert.DeserializeObject(rankings);
foreach (dynamic obj in arr)
{
team_key = obj.team_key;
rank = obj.rank;
}
int index = Array.IndexOf(arr, (string)usableTeamNumber); // <-- This is where the exception is thrown.
Console.WriteLine(index);
// Wait 20 seconds
System.Threading.Thread.Sleep(20000);
Here's the json file I'm using.
I've tried multiple different solutions, none of which worked.
You could just keep the index in variable.
string usableTeamNumber = $"frc{teamNumberString}";
string team_key = "";
int rank = 0;
int index = 0;
int count = 0;
dynamic arr = JsonConvert.DeserializeObject(rankings);
foreach (dynamic obj in arr)
{
team_key = obj.team_key;
rank = obj.rank;
if (usableTeamNumber.Equals(team_key) {
index = count;
}
count++;
}
Console.WriteLine(index);
Create a class that mimics your data structure, like such (only has 3 of the root fields):
public class EventPoints
{
public int point_total { get; set; }
public int rank { get; set; }
public string team_key { get; set; }
}
Then you can Deserialize the object into a list of those objects and you can use LINQ or other tools to query that list:
string teamNumberString = "frc2056";
string TBArankings = #"https://www.thebluealliance.com/api/v2/district/ont/2017/rankings?X-TBA-App-Id=frc2706:ONT-ranking-system:v01";
var rankings = new WebClient().DownloadString(TBArankings);
List<EventPoints> eps = JsonConvert.DeserializeObject<List<EventPoints>>(rankings);
EventPoints sp = eps.Where(x => x.team_key.Equals(teamNumberString)).FirstOrDefault();
Console.WriteLine(eps.IndexOf(sp));
Console.ReadLine();
This is basically a follow up to a previous question I posted of Deserializing JSON to a DataTable. Well the process is nearly finished, this is the code:
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
dynamic d = JObject.Parse(result);
}
var root = JsonConvert.DeserializeObject<RootObject>(result);
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
public class Record
{
public int StatusID { get; set; }
public string Identifier { get; set; }
public string Status { get; set; }
public string StatusDate { get; set; }
public string WorkedBy { get; set; }
public string ContactedOn { get; set; }
public string Email { get; set; }
}
public class RootObject
{
public List<Record> Record { get; set; }
}
Now, the deserialization is working perfectly, but I cannot convert to DataTable. I am using the ToDataTable extension I found in SO, and this snippet is supposed to turn my list into a DataTable:
RootObject.Record.ToDataTable<Record>();
Now of course I cannot do this, since Record is not a static member, but if I make it static, like this:
public static List<Record> record { get; set; }
and change the ToDataTable extension call to
RootObject.record.ToDataTable<Record>();
It breaks the conversion from JSON to List. Using breakpoints if I verify the "root" var its null and has no data, so when it tries to turn it into a DataTable the whole thing crashes since it only has null values.
Your RootObject contains the Record property so you need to use it to create the DataTable like this:
var root = JsonConvert.DeserializeObject<RootObject>(result);
root.Record.ToDataTable<Record>();
What you have tried is to access it as a static memeber of the RootObject class which is in this context wrong becasue the deserialization creates already an instance of RootObject. You now just have to use the Record property that you want to convert to a DataTable.
That's why I think it's not always good to use the var keyword. Sometimes you forget or oversee what type it is. If you wrote:
RootObject root = JsonConvert.DeserializeObject<RootObject>(result);
you might have found the solution by yourself.
I want to get the value in an array and i want to put it in a variable
This is the array {1,eli}
CsvValues = RowData.Split(new string[] {","},
StringSplitOptions.RemoveEmptyEntries); // RowData is {1,eli}
List<string> elements = new List<string>();
foreach (string data in CsvValues)
{
elements.Add(data);
}
and then I want to put it here:
result.Add(new wsSample()
{
id = elements[0],
name = elements[1]
});
How will i add the elements value to id and name?
public class wsSample
{
[DataMember]
public string id { get; set; }
[DataMember]
public string name { get; set; }
}
How is the rest of the input array structured?
If it is elements = {"1","eli", "2","manning"}
then you might be better off using a for loop.
I think this is what you are looking for
List<wsSample> samples = new List<wsSample>();
for(int i=0; i< elements.length-1; ++i)
{
samples.Add(new wsSample()
{
id = elements[i]
name = elements[i+1]
});
i= i+2;
}
I have some data in the following JSON format that I need to parse:
{
"status":0,
"timestamp":"8:20pm",
"routes":[
{
"directions":[
"E Towne",
"ETP"
],
"routeID":"30"
},
{
"directions":[
"Johnson",
"Observatory"
],
"routeID":"81"
}
]
}
Using json.net, I have got want to get the following output:
30 E Towne – ETP
81 Johnson – Observatory
Using the code below, I get the following incorrect output:
30 E Towne – ETP
81 E Towne – ETP
How do I write out the directions array items to the corresponding routeID item? My code:
public class Route
{
public string routeID { get; set; }
public string directions { get; set; }
}
private void routeClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string jsonResults_routes = e.Result;
JObject routeData = JObject.Parse(jsonResults_routes);
JArray routeIdArray = (JArray)routeData["routes"];
JArray routeDirections = (JArray)routeData["routes"][0]["directions"];
List<Route> l = new List<Route>();
for (int i = 0; i < routeIdArray.Count; i++)
{
Route BusRoutes = new Route();
JObject routeIDarrayObject = (JObject)routeIdArray[i];
BusRoutes.routeID = (string)routeIDarrayObject["routeID"];
string sep = " - ";
string bothDirections = String.Join(sep, routeDirections);
List<string> sc = new List<string>();
string[] direction = new string[]{bothDirections};
sc.AddRange(direction);
foreach (string direx in sc)
{
BusRoutes.directions = direx;
}
l.Add(BusRoutes);
}
var newList = l.OrderBy(x => x.routeID).ToList();
lbRoutesData.ItemsSource = newList;
}
#competent_tech is correct in is analysis. If I can propose, I think it'll feel more natural if you work with actual objects. For example:
public class RouteInfo
{
public List<string> Directions { get; set; }
public string RouteID { get; set; }
}
public class RouteData
{
public int Status { get; set; }
public string Timestamp { get; set; }
public List<RouteInfo> Routes { get; set; }
}
And in your method:
var routeData = JsonConvert.DeserializeObject<RouteData>(e.Result);
return routeData.Routes
.Select(r => new Route
{
routeId = r.RouteID,
directions = String.Join(" - ", r.Directions)
})
.OrderBy(r => r.routeId)
.ToList();
Or manipulate your type object in other ways, more naturally.
Edit: For an easy way to generate classes based on a JSON string, go to json2csharp.
This is because your routeDirections is specifically asking for the first element in the array:
JArray routeDirections = (JArray)routeData["routes"][0]["directions"];
You need to move this logic inside the loop and use the current loop indexer:
for (int i = 0; i < routeIdArray.Count; i++)
{
Route BusRoutes = new Route();
JObject routeIDarrayObject = (JObject)routeIdArray[i];
BusRoutes.routeID = (string)routeIDarrayObject["routeID"];
JArray routeDirections = routeIDarrayObject["directions"];