Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 days ago.
Improve this question
I have been trying to display contents of a json file in a textbox for the past 6 hours and got nowhere.
here's the c# code
private thruster Getthruster()
{
string text = File.ReadAllText(#"./thrusters.json");
List<thruster> test = JsonConvert.DeserializeObject<List<thruster>>(text);
textBox1.Text = text;
foreach (var item in test)
{
textBox1.Text = item.type;
}
return Getthruster();
}
public class thruster
{
public string id { get; set; }
public string type { get; set; }
public string placement { get; set; }
}
{
"thruster": [
{
"id": 1,
"type": "tunnel",
"placement": "bow"
},
{
"id": 2,
"type": "tunnel",
"placement": "bow"
},
{
"id": 3,
"type": "azimuth",
"placement": "bow"
},
{
"id": 5,
"type": "azimuth",
"placement": "stern"
},
{
"id": 5,
"type": "tunnel",
"placement": "stern"
},
{
"id": 6,
"type": "azimuth_propulsion"
},
{
"id": 7,
"type": "azimuth_propulsion"
}
]
}
To start, you are running into a StackOverflowException since you are calling the same method (Getthruster()) inside the same method without any exit condition.
After this, your json file seems to be incorrect. You have there a Dictionary<string,thruster[]> and not a thruster[] (Or List).
Your json for a thruster[] or List<thruster> should be something like:
[
{
"id": "1",
"type": "t",
"placement": "top"
},
{
"id": "2",
"type": "t",
"placement": "top"
}
]
you have an object inside of a json string, but you try to serialize it as it is an array. You can use this code that deserializes an array inside of your json
List<thruster> test = JObject.Parse(text)["thruster"].ToObject<List<thruster>>();
Related
I have a large json file and only want to use certain nested properties, here is the file
{
"type": "champion",
"format": "standAloneComplex",
"version": "6.24.1",
"data": {
"Aatrox": {
"version": "6.24.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade",
"blurb": "Aatrox is a legendary warrior, one of only five that remain of an ancient race known as
the Darkin. He wields his massive blade with grace and poise, slicing through legions in a style
that is hypnotic to behold. With each foe felled, Aatrox's ...",
"info": {
"attack": 8,
"defense": 4,
"magic": 3,
"difficulty": 4
},
"image": {
"full": "Aatrox.png",
"sprite": "champion0.png",
"group": "champion",
"x": 0,
"y": 0,
"w": 48,
"h": 48
},
"tags": [
"Fighter",
"Tank"
],
},
"Ahri": {
"version": "6.24.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox",
"blurb": "Unlike other foxes that roamed the woods of southern Ionia, Ahri had always felt a
strange connection to the magical world around her; a connection that was somehow incomplete.
Deep inside, she felt the skin she had been born into was an ill fit for ...",
"info": {
"attack": 3,
"defense": 4,
"magic": 8,
"difficulty": 5
},
"image": {
"full": "Ahri.png",
"sprite": "champion0.png",
"group": "champion",
"x": 48,
"y": 0,
"w": 48,
"h": 48
},
"tags": [
"Mage",
"Assassin"
],
},
It is a very long json file. I have a class that is
public class Champion
{
public string id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string title { get; set;}
}
public class ChampionRoot
{
public Dictionary<string, Champion> champions { get; set; }
}
What I am trying to do is start at the properties inside "Data" and only get "id", "key","name" and "title", and Deserialize those properties into my ChampionRoot class. I have searched and tried many things and cannot get it to work. Here is some of what I've tried in my controller
public IActionResult Champions()
{
var url = #"url.......";
WebClient client = new WebClient();
var download = client.DownloadString(url);
var champions = Newtonsoft.Json.JsonConvert.DeserializeObject<ChampionRoot>(download);
return Json(champions); //This returns null in the view
}
I have also tried using JObject a few different ways and that doesn't work for me either
JObject obj = JObject.Parse(download);
var json = obj["key"]["id"]["name"]["title"]; //throws object reference error
Then I've tried this
JObject obj = JObject.Parse(download);
var champions = Newtonsoft.Json.JsonConvert.DeserializeObject<ChampionRoot>(obj.ToString());
//This also returns null in the view
I have searched and read many answers but I cannot figure it out. The question is how can I only Deserialize those 4 nested properties into an object? The url is http://ddragon.leagueoflegends.com/cdn/6.24.1/data/en_US/champion.json for full json file.
You can use Dictionary<string, Champion> for data property:
public class ChampionRoot
{
public Dictionary<string,Champion> data { get; set; }
}
var champions = Newtonsoft.Json.JsonConvert.DeserializeObject<ChampionRoot>(download);
I have DeserializeObject to a C# object however I have objects with dynamic object names so I have structured it like this:
public class RootObject
{
public string name { get; set; }
public TableLayout table{ get; set; }
}
public class TableLayout
{
public Attributes attributes { get; set; } //Static
public Info info { get; set; } //Static
[JsonExtensionData]
public Dictionary<string, JToken> item { get; set; }
}
So basically any dynamic objects that appear will be added to the dictionary and using JsonExtensionData will populate the rest of the property without creating the object classes. Here is my json:
string json = #"
{
"name": "Table 100",
"table": {
"attributes ": {
"id": "attributes",
"type": "attributes"
},
"info": {
"id": "info",
"type": "info"
},
"item-id12": {
"id": "item-id12",
"type": "Row"
"index": 0
},
"item-id16": {
"id": "item-id16",
"type": "Column"
"parentid": "item-id12"
},
"item-id21": {
"id": "item-id21",
"type": "Column",
"parentid": "item-id12"
}
}
}";
How can I use type ="row" and index value(increments to index 1 to evaluate next row) property to get all columns using parentId of column objects in my Dictionary.
Desired Output:
"item-id12": {
"id": "item-id12",
"type": "Row"
"index": 0
},
"item-id16": {
"id": "item-id16",
"type": "Column"
"parentid": "item-id12"
},
"item-id21": {
"id": "item-id21",
"type": "Column",
"parentid": "item-id12"
}
You can use linq to find your root object
var rootNode = json.table.item.Values
.FirstOrDefault(x => x["type"].Value<string>() == "Row" && x["index"].Value<int>() == 0);
if (rootNode == null)
return; // no such item
Now if this item exists use linq again and get all items from dictionary:
var childNodes = json.table.item.Values
.Where(x => x["parentid"]?.Value<string>() == rootNode["id"].Value<string>());
Next code
var output = new[] {rootNode}.Concat(childNodes);
foreach (var item in output)
Console.WriteLine(item);
will print
{
"id": "item-id12",
"type": "Row",
"index": 0
}
{
"id": "item-id16",
"type": "Column",
"parentid": "item-id12"
}
{
"id": "item-id21",
"type": "Column",
"parentid": "item-id12"
}
P.S. Your input json is invalid, it missing few commas
I'm wondering if someone can elucidate a method to sort a list of objects based on a child object's attribute.
I'm working with the following model:
public class Content
{
public string Id { get; set; }
public List<ContentAttribute> Attributes { get; set; }
}
public class ContentAttribute
{
public string Value { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
Some sample data:
[
{
"Id": "123",
"Attributes": [
{
"Value": "abc",
"Id": "1a",
"Name": "name1"
},
{
"Value": "ghi",
"Id": "2b",
"Name": "name2"
}
]
},
{
"Id": "456",
"Attributes": [
{
"Value": "abc",
"Id": "1a",
"Name": "name2"
},
{
"Value": "def",
"Id": "2b",
"Name": "name3"
}
]
},
{
"Id": "789",
"Attributes": [
{
"Value": "abc",
"Id": "1a",
"Name": "name1"
},
{
"Value": "def",
"Id": "2b",
"Name": "name2"
}
]
}
]
How can I sort the Content objects by the Value of a specific attribute Name? For example, I would like to sort the above data by the Value of 'name2',
meaning the result would be
[
{"Id" : "456"},
{"Id" : "789"},
{"Id" : "123"}
]
Any help is greatly appreciated. (Using c#).
If Attributes always has an element with name name2 and you want an exception if it doesn't then:
var sorted = contents.OrderBy(c => c.Attributes.First(a => a.Name == "name2").Value).ToList();
Or if name2 could be missing and it's not deal breaker then use FirstOrDefault
var sorted = contents.OrderBy(c => c.Attributes.FirstOrDefault(a => a.Name == "name2")?.Value).ToList();
I got a Problem with my API. I want to get a random amout of questions back.
The Model of my question has a list of answers and hints:
public class Question
{
public int Id { get; set; }
public string Text { get; set; }
public string Explanation { get; set; }
public Category Category { get; set; }
public ICollection<Answer> Answers { get; set; }
public ICollection<Hint> Hints { get; set; }
}
normally if i call my get method i get a json with all the lists back
return _ctx.Questions.Include(x => x.Answers).Include(x => x.Hints).ToList();
{
"id": 1,
"text": "Test?",
"explanation": "Test",
"category": null,
"answers": [
{
"id": 1,
"text": "Test",
"isCorrect": true
},
{
"id": 2,
"text": "Test1",
"isCorrect": false
},
{
"id": 3,
"text": "Test2",
"isCorrect": false
},
{
"id": 4,
"text": "Test3",
"isCorrect": false
}
],
"hints": [
{
"id": 1,
"text": "..."
},
{
"id": 2,
"text": "..."
}
]
}
But if I want to get random picks with a orderby i only got empty lists
return _ctx.Questions.Include(x => x.Answers).Include(x => x.Hints).OrderBy(o => Guid.NewGuid()).Take(amount).ToList();
{
"id": 1,
"text": "test",
"explanation": "..-",
"category": null,
"answers": [],
"hints": []
}
Does someone have a Idea to fix this?
After sql need to be a list. I got a similar problem a long time ago.
Hope it s help, was with an older version of Ef.
So you have to add a ToList before the OrderBy.
return _ctx.Questions.Include(x => x.Answers).Include(x => x.Hints).ToList().OrderBy(o => Guid.NewGuid()).Take(amount).ToList();
I usually use json2csharp to generate json classes to c#. But I do have problem. My json is have dynamic depth like this
{
"kategori": [
{
"id": "1",
"namakategori": "Tips & Trick",
"parent_id": "0",
"children": [
{
"id": "348",
"namakategori": "Fotografi",
"parent_id": "1",
"children": []
},
{
"id": "370",
"namakategori": "Hacking",
"parent_id": "1",
"children": []
}
]
},
{
"id": "12",
"namakategori": "Aplikasi",
"parent_id": "0",
"children": [
{
"id": "13",
"namakategori": "Tools",
"parent_id": "12",
"children": [
{
"id": "14",
"namakategori": "Toolsorder",
"parent_id": "13",
"children":[]
},
]
},
]
},
]
}
So how do I generate json classes dynamically so it can be used for my json? In above example I have 3 depth. But if I go to different page maybe it have 4 or more depth.
You don't need to declere your classes dynamically. This should work:
public class Child
{
public string id { get; set; }
public string namakategori { get; set; }
public string parent_id { get; set; }
public List<Child> children { get; set; } // <-- See this
}
public class RootObj
{
public List<Child> kategori { set; get; }
}
To deserialize I'll use Json.Net
var res = JsonConvert.DeserializeObject<RootObj>(json);
You can always use the Newtonsoft.Json
For Instance,
JObject result = (JObject) JsonConvert.DeserializeObject(yourJsonDataHere);
var katObject = result.Property("kategori").Value;
and so on...
PS: Not sure if Newtonsoft.Json is supported on WP7.