.NET classes needed to deserialize JSON string [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parse JSON in C#
I'm trying to deserialize a JSON string from the openlibrary.org in an ASP.NET (4.5) web application using JSON.NET.
My aim is to be able to read the 5 properties below from a single .Net object.
The example JSON
I have is:
{"ISBN:0201558025":
{
"bib_key": "ISBN:0201558025",
"preview": "noview",
"thumbnail_url": "http://covers.openlibrary.org/b/id/135182-S.jpg",
"preview_url": "http://openlibrary.org/books/OL1429049M/Concrete_mathematics",
"info_url": "http://openlibrary.org/books/OL1429049M/Concrete_mathematics"
}
}
I can get it to work fine without the first line, but I'm a bit lost trying to work out how I should structure my classes.
I'm new to JSON and haven't played with C#/VB.NET in a few years so getting very lost.
Update
I have the following code:
Dim url = "http://openlibrary.org/api/books?bibkeys=ISBN:0201558025&format=json"
Dim webClient = New System.Net.WebClient
Dim json = webClient.DownloadString(url)
Dim book As Book = JsonConvert.DeserializeObject(Of Book)(json)
And the class Book:
Public Class Book
Public bib_key As String
Public preview As String
Public preview_url As String
Public info_url As String
End Class
However, book turns up empty.

There is a website called json2csharp - generate c# classes from json:
public class RootObject
{
public string bib_key { get; set; }
public string preview { get; set; }
public string thumbnail_url { get; set; }
public string preview_url { get; set; }
public string info_url { get; set; }
}
The json format is a little off, remove the {"ISBN:0201558025": since you have the ISBN as the bib_key

Try using JSON.Net
or
JavaScriptSerializer Class
or
DataContractSerializer class

I think it can be deserialized as a Dictionary.
new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, BookInfoClass>>(jsonString);

Related

How do I get a value from a Json in .NET 3.5 C#?

On .NET 4.5 I was getting by
string respString= response.Body; // { "name":"John", "age":30, "car":null}
var respObj= JsonConvert.DeserializeObject<dynamic>(respString);
In this case, I was able to create a dynamic object of each property.
However, I have dropped to .NET 3.5, and the dynamic option is not available. How can
I get each property as
string gottenName= respObj.name;
double gottenAge = respObj.age;
etc.
Thank you guys kindly!
Visit a JSON to C# class conversion service, eg: https://www.jsonutils.com/
Paste in the JSON:
{ "name":"John", "age":30, "car":null}
It will generate a Class:
public class Example
{
public string name { get; set; }
public int age { get; set; }
public object car { get; set; }
}
Then you don't need dynamic:
Example respObj= JsonConvert.DeserializeObject<Example>(respString);
You can also parse to C# object using newtonsoft.dll
code will be
JObject jsonResponse = JObject.Parse(respString);
//you can access name value using
var nameValue= (string)jsonResponse["name"]
//respString is jsonstring

Deserialize JSON into an Object(s) using System.Text.Json [duplicate]

This question already has answers here:
Exception parsing json with System.Text.Json.Serialization
(3 answers)
Closed 2 years ago.
I am trying to use the System.Text.Json.Serialization namespace to deserialize the text within a JSON file into an Object named Note, to then access its properties. With the later intent to read-in multiple Note objects, to then store in a List for example.
There don't seem to be many examples on the usage of this namespace, other than within the DOTNET docs https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to
This is my attempt based on the examples given. Which throws the error shown below, if you know what I'm doing wrong please let me know, thanks.
class Note
{
public DateTime currentDate { get; set; }
public string summary { get; set; }
public Note(DateTime _date, string _sum)
{
currentDate = _date;
summary = _sum;
}
}
class Program
{
static void Main(string[] args)
{
//Write json data
string path = #"D:\Documents\Projects\Visual Projects\Notes Data\ThingsDone.json";
DateTime date = DateTime.Now;
string givenNote = "summary text";
Note completeNote = new Note(date, givenNote);
string serialString = JsonSerializer.Serialize(completeNote);
File.WriteAllText(path, serialString);
//Read json data
string jsonString = File.ReadAllText(path);
Note results = JsonSerializer.Deserialize<Note>(jsonString);
Console.WriteLine(results.summary);
}
}
Also I've looked into Json.NET and other options, but I would rather use this one (if possible)
Your Note class needs a parameterless constructor
class Note
{
public DateTime currentDate { get; set; }
public string summary { get; set; }
// add this
public Note()
{
}
public Note(DateTime _date, string _sum)
{
currentDate = _date;
summary = _sum;
}
}
It might be worth thinking if you need your original two parameter constructor. If you removed it, then you could instantiate a new Note like this
var completeNote = new Note
{
currentdate = date,
summary = givenNote
};

Unity C#: parse JSON file into data structure [duplicate]

This question already has answers here:
Serialize and Deserialize Json and Json Array in Unity
(9 answers)
Closed 5 years ago.
I'm trying to create a custom revision quiz program in Unity C# which allows users to load questions into the program using JSON files, structured as below:
{
"question": [
{
"title": "What wave characteristic is measured on the vertical axis?",
"answers": {
"correct": "Amplitude",
"wrong": [
"Frequency",
"Period",
"Speed"
]
}
},
{
"title": "Which of these is a vector quantity?",
"answers": {
"correct": "Velocity",
"wrong": [
"Speed",
"Time",
"Mass"
]
}
}
]
}
I've managed to get my program reading from a file using a StreamReader, but am having a lot of trouble trying to get it into a single data structure.
I have seen other solutions using classes and manually defining structures for their solutions, but I don't know how to go about implementing this for a) as complex a structure as this and b) a structure that can have an arbritrary number of items in it (I'd like to support any number of questions). If the best way is to define these classes, how do I go about referencing items inside them? In the past I've parsed JSON using Python 3.6's json library's json.loads() function, and that worked perfectly, creating a single multidimensional array / dictionary structure that I could work with easily.
To put it simply, I currently have a string that I've read from a file with JSON data in it. How do I synthesise this into a single array that I can easily access using, eg, questions[question][0]["title"], which would return "What wave characteristic is measured on the vertical axis?" in the above case?
Use this site and generate your model.
public class Answers
{
public string correct { get; set; }
public List<string> wrong { get; set; }
}
public class Question
{
public string title { get; set; }
public Answers answers { get; set; }
}
public class RootObject
{
public List<Question> question { get; set; }
}
var model = JsonConvert.DeserializeObject<RootObject>(jsonstring);
That is all
BTW: You can also access to those properties dynamically without declaring any model
var model = JObject.Parse(jsonstring);
var title0 = (string)model["question"][0]["title"];
PS: I used Json.net
I think one way you can create a single data structure in your application by using the JSON given above is using the "paste special feature" of visual studio.Once you select it from the edit menu you have option to create class from JSON by just pasting any valid JSON.
I get the following class after pasting your JSON related to Questions:-
public class Rootobject
{
public Question[] question { get; set; }
}
public class Question
{
public string title { get; set; }
public Answers answers { get; set; }
}
public class Answers
{
public string correct { get; set; }
public string[] wrong { get; set; }
}
Single Rootobject class consists of the Question array.There different classes automatically created by visual studio related to Question and Answers.
You can deserialize the JSON values into your RootObject using JSON.NET desrialization:
var questions= JsonConvert.DeserializeObject<RootObject>(jsonString);

C# - De-serialize class having byte array from string [duplicate]

This question already has answers here:
Newtonsoft.Json deserializing base64 image fails
(3 answers)
Closed 5 years ago.
I have a class
[Serializable]
public class DocumentMetadataBEO
{
public Guid ItemId { get; private set; }
public byte[] HashValue { get; set; }
}
I am receiving string having both of the above value.
However when i try to deserialize as below -
documentMetadata = JsonConvert.DeserializeObject<DocumentMetadataBEO>(responseFromServer);
HashValue property is getting set null. How can I deserialize it?
Here is the Json format, we get from server
"{
\"ItemId\":\"a1606584-9b9e-4bba-845f-e775eb5ebda5",
\"HashValue\":\"UHj5WO00uD5MIeCEr0Bt8i03iMrqUfILky7wSiqIn7g=\
"}"
With a newer version of Json.NET, it is working out of the box.

Trying to convert a xml file to an object [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I was wondering what your opinion about this would be. I'm trying to convert an xml file to a .net object. It's a xml file from the World of Warcraft armory. Here is an example.
<?xml version="1.0" encoding="UTF-8"?>
<baseStats>
<strength attack="48" base="48" block="-1" effective="58"/>
<agility armor="114" attack="-1" base="47" critHitPercent="4.27" effective="57"/>
<stamina base="70" effective="1186" health="11680" petBonus="-1"/>
<intellect base="198" critHitPercent="10.41" effective="1529" mana="22655" petBonus="-1"/>
<spirit base="190" effective="770" healthRegen="39" manaRegen="503"/>
<armor base="2150" effective="2150" percent="12.37" petBonus="-1"/>
</baseStats>
I've thought of 2 ways to convert this to an object and I'd like to hear your opinion about it. Ill show them.
class BaseStats{
public int StrengthAttack{get;set;}
public int StrengthBase{get;set;}
public int StrengthBlock{get;set;}
...
public int ArmorBase{get;set;}
public int ArmorEffective{get;set;}
...
}
or
class BaseStats{
public Strength Strength{get;set;}
public Armor Armor{get;set;}
public class Strength{
public int Attack{get;set;}
public int Base{get;set;}
public int Block{get;set;}
}
public class Armor{
public int Base{get;set;}
public int Effective{get;set;}
}
}
Do you see what I'm trying here. What would be your opinion about each of those ways. Or can you think of any others?
Classless Design using an Anonymous Type
Here's another way, with .NET 3.5, if you don't want to design an explicit class you can build the object dynamically as an anonymous type; one caveat being the object properties are read-only after being initialized.
Use the XML LINQ classes to query the XML content with.
using System;
using System.IO;
using System.Xml.Linq;
Load up the XML string and query it to create an object.
// 1. Load your string into a document.
XDocument xdoc = XDocument.Load(new StringReader(my_WoW_XML_String));
// 2. Create the anonymous type...
var statsObject = new
{
StrengthInfo = new
{
Attack = int.Parse(xdoc.Element("strength").Element("attack").Value),
Base = int.Parse(xdoc.Element("strength").Element("base").Value),
Block = int.Parse(xdoc.Element("strength").Element("block").Value),
Effective = int.Parse(xdoc.Element("strength").Element("effective").Value),
},
AgilityInfo = new
{
Armor = int.Parse(xdoc.Element("agility").Element("armor").Value),
Attack = int.Parse(xdoc.Element("agility").Element("attack").Value),
Base = int.Parse(xdoc.Element("agility").Element("base").Value),
CritHitPercent = int.Parse(xdoc.Element("agility").Element("critHitPercent").Value),
Effective = int.Parse(xdoc.Element("agility").Element("effective").Value),
}
// Do the same with <spirit> and <armor> elements, etc.
// Include only the properties you want from the XML.
}; // end anonymous object.
Use your anonymous object normally like so:
Console.Write("strength: attack={0}, effective={1}; armor agility={2}",
statsObject.StrengthInfo.Attack,
statsObject.StrengthInfo.Effective,
statsObject.AgilityInfo.Armor);
// Do whatever you want with the object version of WoW stats.
If you have multiple XML files to process with the same schema then just wrap all the above in a loop to process one at a time.
If you have the XSD schema (or can create one), I've used LinqToXsd to create some quick objects. The nice thing about LinqToXsd is that it creates methods you can use to easily parse XML into your objects.
Microsoft has released it as Open Source - and you can simply use a command-line call to pass in your .xsd and it will generate a .cs file with all of your classes.
class CElement
{
public int? attack { get; set; }
public int? base { get; set; }
public int? block { get; set; }
public int? effective { get; set; }
public int? petBonus { get; set; }
public int? mana { get; set; }
public int? healthRegen { get; set; }
public int? manaRegen { get; set; }
public double? critHitPercent { get; set; }
public double? percent { get; set; }
}
class CBaseStats
{
public CElement strength;
public CElement agility;
public CElement stamina;
public CElement intellect;
public CElement spirit;
public CElement armor;
}
If you got complete xml,
1. generate xsd from xml using the xsd.exe tool
2. generate class from the generated xsd using xsd.exe tool
http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx

Categories