Get value from JSON with JSON.NET - c#

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;

Related

clean CSV column value as JSON to C# object

I've got some text written in a CSV column that is supposed to represent a JSON string:
{
"text": "foil text1",
"image": "existing_image_uploaded.png",
"score": false
},
{
"text": "foil text2",
"image": "existing_image_uploaded2.png",
"score": true
}
This CSV text comes out as the following string:
var foils = "{\n \"text\": \"foil text1\",\n \"image\": \"existing_image_uploaded.png\",\n
\"score\": false\n},\n\n{\n \"text\": \"foil text2\",\n \"image\":
\"existing_image_uploaded2.png\",\n \"score\": true\n}"
I would like to convert this text to a List of the following class
public class FoilJSON{
public string text {get;set;}
public string image {get;set;}
public bool score {get;set;}
}
This is the way I would like to convert the JSON to a List of FoilJSON
var converted = JsonSerializer.Deserialize<List<FoilJSON>>(foils);
However the string foils is not in a proper JSON format to convert to a base class.
Is there a C# library or method to remove all the CSV garbage within the foils string?
var foils = "[{\n \"text\": \"foil text1\",\n \"image\": \"existing_image_uploaded.png\",\n
\"score\": false\n},\n\n{\n \"text\": \"foil text2\",\n \"image\":
\"existing_image_uploaded2.png\",\n \"score\": true\n}]"
You have to have square brackets to have a list otherwise you simply have two objects separated by a comma... doesn't really make it a correct json
try this, this code will convert your invalid json string to a json string of JArray of JObjects. After this you can use a serializer to deseialize a json string to an instance of c#
foils = "[" + foils + "]";
List<FoilJSON> converted = System.Text.Json.JsonSerializer.Deserialize<List<FoilJSON>>(foils);

Split a string at the first occurrence of a character after matching string

The Data:
{
\"value\": 17.11, \"year\": 2015, \"sub\": [ {\"x\": 0, \"y\": 0.94 }, {\"x\": 1, \"y\": 1.08 }]
}
,
{
\"value\": 17.23, \"year\": 2015, \"sub\": [ {\"x\": 0, \"y\": 0.23 }, {\"x\": 1, \"y\": 1.22 }]
}
I've got a list of JSON objects in a format you see above and I need to split the objects at the ',' between the two objects. The problem is that there are other commas present in the file. Apart from actually serializing the JSON into a List, is there any other way to get this done?
I'm trying to get the data into a string array like:
string[] split = json.split(',');
Note that the data above is actually all coming on one line, there aren't any line breaks, tabs, or anything. I organized it above to make it more readable.
Writing your own parser would be tricky. It would be much easier if you used a JSON parser. Your format is not valid JSON, but it would be with surrounding []. So if you insert those characters, you should be able to use a real parser:
using Newtonsoft.Json
// ...
var objects = JsonConvert.DeserializeObject<List<SomeClass>>("[" + json + "]");

Deserialize Object (Newtonsoft) with an array of arrays inside

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

String.Format: Input string was not in a correct format [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
The following code keep giving me error saying Input string was not in a correct format, but I am pretty sure it is right, isn't it?
int id = 112;
String[] newData = { "1", "2", "21", "reidb", "reidb", "reidb", "reidb", "aa",
"Some description", "11", "2012-02-28", "2012-01-29", "true", "1", "1",
"true", "note note note", "true", "1", "2011-12-03", "45"};
String data = "{ cmd: \"save magellan deal\", data: { id: {0} , AId: {1}, " +
"CId: {2}, CCId:{3}, LA: \"{4}\", BA: \"{5}\" , " +
"LSA: \"{6}\" , BSA: \"{7}\" , \"path: \"{8}\"," +
"dscp: \"{9}\", SI: \"{10}\", CD: \"{11}\", " +
"period: \"{12}\", IsStatic: {13}, LSD: {14}, LC: {15}, RB: {16},} " +
"Notes: \"{17}\", IsEE: {18}, RBy: {19}, DPDD: \"{20}\", LId: {21} } }";
String cmd = String.Format(data, id.toString(), newData);
Anyone any ideas?
=== EDIT ===
after fixing the braces, a new error of "Index (zero based) must be greater than or equal to zero and less than the size of the argument list." is given. the newData has 21 and plus the id.toString(), should be exact 22?
Escape the "{", "}" (by duplicating them) in the format string:
"{{ cmd: \"save magellan deal\", data: {{ id: {0} , AId: {1}, " +
"CId: {2}, CCId:{3}, LA: \"{4}\", BA: \"{5}\" , " +
"LSA: \"{6}\" , BSA: \"{7}\" , \"path: \"{8}\"," +
"dscp: \"{9}\", SI: \"{10}\", CD: \"{11}\", " +
"period: \"{12}\", IsStatic: {13}, LSD: {14}, LC: {15}, RB: {16},}} " +
"Notes: \"{17}\", IsEE: {18}, RBy: {19}, DPDD: \"{20}\", LId: {21} }} }}"
And you have 22 elements in the format string and 21 in the array.
You have 21 elements in newData but use 22 placeholders (numbered 0 to 21).
Also, you must escape literal '{' in your input data
Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported.
http://msdn.microsoft.com/en-us/library/txafckwd.aspx
I've said as much in the comments, but I think it's worth an answer by now:
Don't use string.Format (in this case). It's slower, and less readable. Just use plain string concatenation with meaningful variable names if you need complex concatenations - these will be faster and more maintainable. Faster because for a fixed number of segments plain + is the fastest option due to compiler optimizations, and more maintainable because the reader can see the context within the string in which the variable is put.
As Hans Passant noted, it looks like you're making a javascript literal. If that's the case, consider a Json serializer like Json.NET instead:
JsonConvert.SerializeObject(new {
cmd = "save magellan deal",
data = new {
id = 12345, AId = 1, CId = 2, CCId = 21,
LA = "reidb", BA = "reidb", LSA = "reidb", BSA = "reidb",
path = "aa", dscp = "Some description", SI = 11,
CD = "2012-02-28", period = "2012-01-29",
IsStatic = true, LSD = 1, LC = 1, RB = true,
},
Notes = "note note note",
IsEE = true, RBy = 1, DPDD = "2011-12-03", LId = 45
})
While Json.NET does support DateTime serialization, there's not standardized format for dates in JS, so these are serialized as strings in an iso 8601 format. This might not be what you need, hence the date strings in this example - I'd try the iso format first, though, as that's the simplest solution.
In addition to escaping your curly braces also try changing your String[] definition to:
int id = 112;
String[] newData = {id.ToString(), "1", "2", "21", "reidb", "reidb", "reidb", "reidb", "aa",
"Some description", "11", "2012-02-28", "2012-01-29", "true", "1", "1",
"true", "note note note", "true", "1", "2011-12-03", "45"};
and change your String.Format to:
String cmd = String.Format(data,newData);
What
String cmd = String.Format(data, id.toString(), newData);
does is: trying to format the String data , using just 2 strings..not 22!!
Which ones?...1)id.ToString() and 2)newData.ToString()
Thats obviously wrong
How you can see that this is the problem...? Leave just {0} and {1} in data string and print it.It compiles ok and see what you get.
Of course you have to use {{ instead of { where you want a string literal
Fully working Solution:
int id = 112;
String[] newData = { id.ToString(),"1", "2", "21", "reidb", "reidb", "reidb", "reidb", "aa",
"Some description", "11", "2012-02-28", "2012-01-29", "true", "1", "1",
"true", "note note note", "true", "1", "2011-12-03", "45"};
String data = "{{ cmd: \"save magellan deal\", data: {{ id: {0} , AId: {1}, " +
"CId: {2}, CCId:{3}, LA: \"{4}\", BA: \"{5}\" , " +
"LSA: \"{6}\" , BSA: \"{7}\" , \"path: \"{8}\"," +
"dscp: \"{9}\", SI: \"{10}\", CD: \"{11}\", " +
"period: \"{12}\", IsStatic: {13}, LSD: {14}, LC: {15}, RB: {16},}} " +
"Notes: \"{17}\", IsEE: {18}, RBy: {19}, DPDD: \"{20}\", LId: {21} }} }}";
String cmd = String.Format(data, newData);

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