Deserialize Object (Newtonsoft) with an array of arrays inside - c#

So I need to convert this string into an object essentially.
{
"character_list": [
{
"character_id": "5428018587875812257",
"name": {
"first": "gixtr2",
"first_lower": "gixtr2"
},
"faction_id": "3",
"head_id": "1",
"title_id": "17",
"times": {
"creation": "1355333636",
"creation_date": "2012-12-12 17:33:56.0",
"last_save": "1385855627",
"last_save_date": "2013-11-30 23:53:47.0",
"last_login": "1385850955",
"last_login_date": "2013-11-30 22:35:55.0",
"login_count": "334",
"minutes_played": "16492"
},
"certs": {
"earned_points": "13219",
"gifted_points": "384",
"spent_points": "12538",
"available_points": "1065",
"percent_to_next": "0.05122222222318"
},
"battle_rank": {
"percent_to_next": "4",
"value": "50"
},
"profile_id": "14",
"daily_ribbon": {
"count": "5",
"time": "1385787600",
"date": "2013-11-30 05:00:00.0"
}
}
],
"returned": 1
}
I get that character_list is an array but there are other objects INSIDE that array. I would like help parsing those objects into the main object.
Code
It's rather lengthy so it's in a text file. I'm doing this in c#.NET.

You're not that far off the mark. The main problem is that character_list is an array in your JSON, but the character_list property in your JsonHttp class does not represent an array or a list, so it won't deserialize properly.
Here's what you need to do:
First rename your character_list class to Character. This class represents the stats for a single character in your game, does it not?
In your JsonHttp class, change the type of your character_list property from character_list to List<Character>.
In your Character class, either rename your daily_ribbons property to daily_ribbon (singular), or mark it with [JsonProperty("daily_ribbon")]. The property name in the JSON is singular, so it needs to match your class somehow.
With those changes, you should be able to deserialize your JSON and extract the data as shown below (where json is your JSON string as posted in your question):
JsonHttp obj = JsonConvert.DeserializeObject<JsonHttp>(json);
foreach (Character c in obj.character_list)
{
Console.WriteLine("Character id: " + c.character_id);
Console.WriteLine("Name: " + c.name.first);
Console.WriteLine("Faction id: " + c.faction_id);
Console.WriteLine("Head id: " + c.head_id);
Console.WriteLine("Title id: " + c.title_id);
Console.WriteLine("Profile id: " + c.profile_id);
Console.WriteLine("Creation date: " + c.times.creation_date);
Console.WriteLine("Last login date: " + c.times.last_login_date);
Console.WriteLine("Last save date: " + c.times.last_save_date);
Console.WriteLine("Login count: " + c.times.login_count);
Console.WriteLine("Minutes played: " + c.times.minutes_played);
Console.WriteLine("Earned points: " + c.certs.earned_points);
Console.WriteLine("Gifted points: " + c.certs.gifted_points);
Console.WriteLine("Spent points: " + c.certs.spent_points);
Console.WriteLine("Available points: " + c.certs.available_points);
Console.WriteLine("Percent to next cert: " + c.certs.percent_to_next);
Console.WriteLine("Battle rank value: " + c.battle_rank.value);
Console.WriteLine("Percent to next rank: " + c.battle_rank.percent_to_next);
Console.WriteLine("Daily ribbon count: " + c.daily_ribbons.count);
Console.WriteLine("Daily ribbon date: " + c.daily_ribbons.date);
}
Here is a Fiddle with the full working code: https://dotnetfiddle.net/Zt6aWd

Related

how to evenly space out information?

I have some vehicle information that I want to send in an email.
I have all code working but spacing out the information is a problem. Each vehicle has a checklist and that checklist then gets emailed. So I loop through the list and get the defect and the comment.
foreach (var item in chkList.CheckItems)
{
if (item.Defect == true)
{
defect += item.ItemTitle + " " + item.Comment + "\n";
}
}
if (hasDefect == true)
{
Utils.ChecklistSendMail("Checklist", ToAddresses.Split(';'),
"Vehicle Reg: " + reg + "\n" +
"Checklist No: " + chkList.CheckListNo + "\n"+
"Date: " + ChecklistDate.ToShortDateString() + "\n" +
"Defects: Comments: " + "\n" +
defect);
}
Email then looks like this:
Vehicle Reg: XLZ 8194
Checklist No: 0
Date: 22/03/2016
Defects: Comments:
Vehicle Secure comment1
Brakes comment2
I want the defects and the comments to be displayed like this:
Defects: Comments:
Vehicle Secure comment1
Brakes comment2
How do I evenly space out the defects and the comments?
You can use string.Format which supports automated padding:
string s = string.Format("{0,-20}{1}", "hello", "world");
Which outputs:
hello world
If you do that for every line, and you find a good distance (20 in my sample code), you will be fine. This all assumes the use of a mono-spaced font.
Use String.Format with the width specifier:
if (item.Defect == true)
{
defect += string.Format("{0,-20} {1,-10}\n", item.ItemTitle, item.Comment);
}
You could also use StringBuilder.AppendFormat if performance becomes an issue.
If you want to guarantee that the columns are aligned, even with a client that uses proportional fonts, then consider rendering as HTML and using a <table> instead.

Concatenating multiple strings with nullables

I Have a messagebox to display some text and data (if existing) within database. The current Issue is trying to show nulls and trying to convert to ShortDate. I've taken two approach but none quite work in the way I need.
The first approach uses Ternary concatenation within the string but it behaves really weird.
DialogResult DuplicateMessage = MessageBox.Show("A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ",
,"Possible Duplicate Client", MessageBoxButtons.YesNo);
Currently The message box only shows the line breaks and the Date Of birth. Not even the text "Date of Birth"
If I remove Tertiary and conversion and simply have
DialogResult DuplicateMessage = MessageBox.Show("A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB
,"Possible Duplicate Client", MessageBoxButtons.YesNo);
This works, shows everything. Only issue is that the Date of birth is in the wrong format. Was wondering how do I make it so the date is in short date format and will show everything.
all Properties Of 'DuplicateName' are nullable,
I suspect this is a problem with operator precedence using the conditional operator. It's likely including string concatenations as part of the condition being tested, rather than as part of the result. You can explicitly enclose the elements of that operator with parentheses to identify which strings belong therein and which do not:
"\n Date of Birth: " + (DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ")
Additionally, if DOB is a DateTime? then you can simplify your code a little:
"\n Date of Birth: " + (DuplicateName.DOB.HasValue ? DuplicateName.DOB.Value.ToString("yyyy-mm-dd") : " ")
There's no need to use Convert on Nullable<T> types, you can more easily (and safely) make use of the HasValue and Value properties.
You can fix it by using another pair of parentheses:
(DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB))
In your first case, you're concatenating a huge string together (because you don't use any parentheses) and then testing that for null. It's equivalent to this:
var stringToTest = "A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB;
DialogResult DuplicateMessage =
MessageBox.Show(stringToTest != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ",
,"Possible Duplicate Client", MessageBoxButtons.YesNo);

Textbox not showing output in MVC [duplicate]

This question already has answers here:
How to display the text in MVC?
(4 answers)
Closed 8 years ago.
I want to show a output in textbox in MVC. But its not displaying anything. I used the following code and i attached screenshot below:
#Html.TextAreaFor(up => up.CompileOutput)
foreach (CompilerError CompErr in results.Errors)
{
userProgram.CompileOutput = "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
return View(userProgram);
The first image shows that the output is binded with that particular textbox. But in browser (image 2) shows nothing in the textbox (red colour)
I am even wondering why you did not got an exception. return view(string) will look for a view with the string parameter as name, it will not show the text.
I would suggest you use ViewBag instead. So you set your error text in a property you name as follow:
foreach (CompilerError CompErr in results.Errors)
{
userProgram.CompileOutput = "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
ViewBag.ErrorText = userProgram.CompileOutput;
You can later on retrieve the value by simply calling ViewBag.ErrorText from you Razor view
Why not try doing it another way?
#Html.TextArea("CompileOutput", userProgram.CompileOutput)

Get value from JSON with JSON.NET

I try to use http://www.codeplex.com/Json to extract values ​​from a json object.
I use imdbapi.com and they return json like this:
{"Title": "Star Wars", "Year": "1977", "Rated", "PG", "Released", "25 May 1977", "Genre", "Action, Adventure, Fantasy, Sci-Fi "" Director ":" George Lucas "," Writer "," George Lucas "," Actors ":" Mark Hamill, Harrison Ford, Carrie Fisher, Alec Guinness, "" Plot ":" Luke Skywalker leaves his home planet, teams up With Other Rebels, and Tries to save Princess Leia from the evil clutch of Darth hrs 1 min "," Rating ":" 8.8 "," Votes ":" 397318 "," ID ":" tt0076759 "," Response ":" True "}
How can I pick up such title, rating, Year? and save it to my object?
This line return correct json:
JObject jObject = JObject.Parse (json);
Now I just need help picking out the data I want. any suggestions?
This should help you http://james.newtonking.com/pages/json-net.aspx
string json = #"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
//This will be "Apple"
string name = (string)o["Name"];
JObject API documentation
I believe you are interested in the .Item[key] collection that returns JTokens.
Full Documentation
class TypeHere{
string Name {get;set;}
}
TypeHere object = JsonConvert.DeserializeObject< TypeHere >(jsonString)
// Ex. output
object.Name;

C# StringBuilder with Quotes (forJSON)

I have build a JSON string (to be posted to a web service), and I used the C# StringBuilder class to do this. The problem is, that when I insert quotes, the StringBuilder class escapes them.
I am currently building the JSON string as such:
StringBuilder dataJSON= new StringBuilder();
dataJSON.Append("{");
dataJSON.Append(" " + Convert.ToChar(34) + "data" + Convert.ToChar(34) + ": {");
dataJSON.Append(" " + Convert.ToChar(34) + "urls" + Convert.ToChar(34) + ": [");
dataJSON.Append(" {" + Convert.ToChar(34) + "url" + Convert.ToChar(34) + ": " + Convert.ToChar(34) + domain + "/" + path[0] + Convert.ToChar(34) + "}");
dataJSON.Append(" ,{" + Convert.ToChar(34) + "url" + Convert.ToChar(34) + ": " + Convert.ToChar(34) + domain + "/" + path[1] + Convert.ToChar(34) + "}");
dataJSON.Append(" ]");
dataJSON.Append(" }");
dataJSON.Append("}");
However, the command:
dataJSON.ToString(); results in the string:
{ \"data\": { \"urls\": [ {\"url\": \"domain/test1.html\"} , {\"url\": \"domain/test2.html\"} ] }}
Notice the escaped quotes? This is really screwing me up, because the server can't handle the slashes.
My desired (which posts fine to my server when I use PHP) should be:
{ "data": { "urls": [ {"url": "domain/test1.html"} , {"url": "domain/test2.html"} ] }}
Is there ANY way to get a string in C# to include quotes that will result in the desired string?
Many thanks!
Brett
The QuickWatch/Watch window will add the extra \ in. If you view it in the Text Visualizer, you will not see them:
QuickWatch:
"{ \"data\": { \"urls\": [ {\"url\": \"domain/path1\"} ,{\"url\":
\"domain/path2\"} ] }}"
Visualizer (the actual output):
{ "data": { "urls": [ {"url": "domain/path1"} ,{"url": "domain/path2"} ] }}
The \ indicates that the quotes have been escaped and will be included in the final string as you're expecting them to be. I.e. there's nothing wrong with your output.
NB. I used "\"" instead of Convert.ToChar(34) when I tested this.
You may have more luck using the Newtonsoft.JSON library, or alternately just escaping the slashes yourself as \" in your string literals instead of using Char(34).
dataJSON.Append(" \"data\": {");

Categories

Resources