Deserialize a Json string (in C#) without Json.Net - c#

I use the following lines to deserialize simple Json strings like this:
string jSon = "{\"FirstName\":\"Foo\", \"LastName\":\"Bar\"}";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Person personDeserialized = oSerializer.Deserialize<Person>(jSon);
Then, I add the "personDeserialized" object to the database with Entity Framework.
The problem is that this method doesn't work if I have the following data :
string jSon = "{
\"FirstName\":\"Foo\",
\"LastName\":\"Bar\",
\"Hobbies\":
[
{\"Sport\":\"FootBall\"},
{\"Music\":\"Rock\"},
]
}";
Of course, the Person class contains references to the Hobbie's one.
So, is there a way, and without the jSon.NET library, to add the "Hobbies" object automatically to the personDeserialized object?
Thanks,
Regards.

Have you tried using the new .NET DataContractJsonSerializer?
I believe I works much better than the JavaScriptSerializer that you're using.

Related

How to deserialize encapsulated table of objects in .NET Core from JSON file?

I want to retrieve a collection of football leagues from an external api. The response from the server comes as shown below:
{
"api": {
"results": 1496,
"leagues": [
{
"league_id": 1,
.....
The returned object constists of an "api" field which hold "results" and "leagues". I would like deserialize the code and map it to League class objects in my code.
var jsonString = await ExecuteUrlAsync(filePath, url);
var results = JsonConvert.DeserializeObject<IEnumerable<LeagueEntity>>(jsonString);
jsonString is correct, but when the program hits second line I get an exception:
Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.IEnumerable".
I need to get to the "leagues" field in JSON file, and ignore the rest of the response. How to achieve that?
Assuming your LeagueEntity corresponds to the api.leagues[*] objects, you can use JsonConvert.DeserializeAnonymousType() to pick out and deserialize the interesting portions of the JSON:
var leagues = JsonConvert.DeserializeAnonymousType(jsonString,
new { api = new { leagues = default(List<LeagueEntity>) } })
?.api?.leagues;
This avoids the need to create an explicit data model for the api.leagues container objects. It should also be more efficient than pre-loading into a JToken hierarchy, then as a second step selecting and deserializing the api.leagues array.
Demo fiddle here.
(Alternatively, you could auto-generate a complete data model for the entire JSON using one of the answers from How to auto-generate a C# class file from a JSON string.)

Convert string to json using C#

i am beginner to C#, i have a very long string and want to convert it to json, string is
{"employees":
[{"id":0,"level":0,"label":"Product Names","subitems":
[{"id":0,"level":1,"label":"Soren","subitemslevel3":
[{"id":0,"level":2,"label":"AAAA"},{"id":0,"level":2,"label":"bbb"}]},
{"id":0,"level":1,"label":"Test","subitemslevel3":
[{"id":0,"level":2,"label":"111"},{"id":0,"level":2,"label":"2222"}]}]},
\
any ideas?
You can do something like this:
var jobject = JsonConvert.DeserializeObject<JObject>(yourVariable);
this is using Newtonsoft's json library that you can get from nuget.
Also JObject is the C# equivalent to a JSON object so that's probably something you'll want to use.
u an also use,
JObject.Parse(urJsonString);
JObject is in Newtonsoft.Json.Linq namespace.
You need to Deserialize your string as follows :
// Your string here
string str = #"[{"categories":
[{"id":0,"level":0,"label":"Product Names","subitems":
[{"id":0,"level":1,"label":"Soren","subitemslevel3":
[{"id":0,"level":2,"label":"AAAA"},{"id":0,"level":2,"label":"bbb"}]},
{"id":0,"level":1,"label":"Test","subitemslevel3":
[{"id":0,"level":2,"label":"111"},{"id":0,"level":2,"label":"2222"}]}]},
{"id":0,"level":0,"label":"Product texts","subitems":
[{"id":0,"level":1,"label":""},{"id":0,"level":1,"label":"<p>Disney <strong>Princess<\/strong><\/p>\n"},{"id":0,"level":1,"label":"<p>Machines & Mechanisms - <strong>Middle<\/strong><\/p>\n"},{"id":0,"level":1,"label":"64738574"},{"id":0,"level":1,"label":"8765432"},{"id":0,"level":1,"label":"a"},{"id":0,"level":1,"label":"aa"},{"id":0,"level":1,"label":"ab"},{"id":0,"level":1,"label":"abe"},{"id":0,"level":1,"label":"aD!?"},{"id":0,"level":1,"label":"Bionicle"},{"id":0,"level":1,"label":"Disney Princess"},{"id":0,"level":1,"label":"er"},{"id":0,"level":1,"label":"foo foo"},{"id":0,"level":1,"label":"hej"},{"id":0,"level":1,"label":"igen"},{"id":0,"level":1,"label":"meta"},{"id":0,"level":1,"label":"metadata"},{"id":0,"level":1,"label":"metadata from kafka"},{"id":0,"level":1,"label":"Metatest"},{"id":0,"level":1,"label":"q"},{"id":0,"level":1,"label":"Simpsons"},{"id":0,"level":1,"label":"test"},{"id":0,"level":1,"label":"Test 123"},{"id":0,"level":1,"label":"Test Metadata 123"}]},{"id":0,"level":0,"label" :"Specialist Terms","subitems":[{"id":0,"level":1,"label":"meta"},{"id":0,"level":1,"label":"new category 1111"},{"id":0,"level":1,"label":"secret category"}]}]}]";
// DeSerialize your object
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

Get partial object list from JSON C#

I am calling a RESTful service in C# and the result is similar to this:
{
"blabla":1,
"bbb":false,
"blabla2":{
"aaa":25,
"bbb":25,
"ccc":0
},
"I_want_child_list_from_this":{
"total":15226,
"max_score":1.0,
"I_want_this":[
{
"A":"val1",
"B":"val2",
"C":"val3"
},
{
"A":"val1",
"B":"val2",
"C":"val3"
}
...
]
"more_blabla": "fff"
...
}
I want to get the "I_want_this" part as a list of object or JObject
Is there something like
(JObject)responseString["I_want_child_list_from_this"]["I_want_this"]
more generically:
(JObject)responseString["sub"]["sub_sub"]
I am using Newtonsoft.Json
Thanks!
First off, I would create a class that represents the JSON structure returned from the service call. (http://json2csharp.com/ great utility for auto-generating classes from JSON)
Second, if you are not using Newtonsoft.Json library, I would recommending grabbing that library.
Lastly, use Newtonsoft to deserialize the JSON from the service call into the class you created:
var json = Service.GetJson();
var yourDesiralizedJson = JsonConvert.DeserializeObject<YourJsonToCSharpClass>(json);
var listYouWant = yourDesiralizedJson.IWantChildList.IWantThis;
The below link is appears to be close to the solution as the requester using NewtonSoft.Json as his api to manipulate the object. Appreciate the solutions from other users as well.
look at e.g. here newtonsoft.com/json/help/html/SerializingJSONFragments.htm
The best solution (imo) is to define classes that describe your JSON schema then use DeserializeObject, as suggested by ertdiddy. As a shortcut, you can use DeserializeAnonymousType with incomplete definitions of your schema, taking advantage of JSON's leniency. In your case, this code is working for me:
var testDataFromQuestion = #"
{
""blabla"":1,
""bbb"":false,
""blabla2"":{
""aaa"":25,
""bbb"":25,
""ccc"":0
},
""I_want_child_list_from_this"":{
""total"":15226,
""max_score"":1.0,
""I_want_this"":[
{
""A"":""val1"",
""B"":""val2"",
""C"":""val3""
},
{
""A"":""val1"",
""B"":""val2"",
""C"":""val3""
}
],
""more_blabla"": ""fff""
}";
var anonymousDefinitionOfJson = new {
I_want_child_list_from_this = new {
I_want_this = new Dictionary<string, string>[] {}
}
};
var fullDeserializationOfTestData =
JsonConvert.DeserializeAnonymousType(testDataFromQuestion,
anonymousDefinitionOfJson);
var stuffYouWant = insterestingBits.I_want_child_list_from_this.I_want_this;
Console.WriteLine($"The first thing I want is {stuffYouWant[0]["A"]}");
This outputs the expected value "val1". I'm anonymously defining the minimal classes that get just the data you want, then I'm asking Newtonsoft to parse just enough to populate those classes.

Deserialize json passed by javascript to c#

Im currently trying to deserialize json that got bassed by javascript this way:
window.external.handlemessage(json);
And its being handled by c# like this:
public void handlemessage(string json)
{
JavaScriptSerializer deserializer = new JavaScriptSerializer();
Dictionary<string, object> deserializedDictionary1 = (Dictionary<string, object>)deserializer.Deserialize(json, typeof(object));
Dictionary<string, object> deserializedDictionary2 = deserializer.Deserialize<Dictionary<string, object>>(json);
object objDeserialized = deserializer.DeserializeObject(json);
}
The passing works fine with plain text for example but just not with json..
I've tried several things such as the deserialize example i provided in the handlemessage but the json just returns invalid basicly. And several other examples ive tried just didn`t do it either.
I have tried to deserialized the json with java and serialized it again without no results (incase there were some flaw).
Also Im trying to deserialize the data without knowing the json structure.
Is it even possible to pass json by javascript and unserializing it with c#?
Also Im trying to deserialize the data without knowing the json structure.
For that you want to use C#'s dynamic type:
JavaScriptSerializer js = new JavaScriptSerializer();
dynamic v = js.Deserialize<dynamic>("{\"text\" : \"hi\"}");
In fact you can start there for all your data until you understand how the object is being mapped.

Convert Struct to JSON

I have a struct, I want to convert it to JSON and save it as local file.
I couldn't find any source that explain how to convert a C# struct into a JSON.
I am using a console application for that, not a webservice/web, etc.
JavaScriptSerializer Class
var serializer = new JavaScriptSerializer();
YourStruct myStruct = new YourStruct(x,y,z);
var json = serializer.Serialize(myStruct);
JSON.NET
The other alternative JSON.net, it do not depends on System.Web.* assemblies:
YourStruct myStruct = new YourStruct(x,y,z);
var json = JsonConvert.SerializeObject(myStruct);
I would recommend using JSon.net. You can then do something like:
string json = JsonConvert.SerializeObject(myObj); // myObj is the struct you want to serialize
File.WriteAllText("Foo.json", json); //Write the text to Foo.json
Install https://www.nuget.org/packages/Newtonsoft.Json/
Use JsonConvert.SerializeObject(structName) to serialize object. Do not forget to change argument name to yours

Categories

Resources