this is my JSON
[{"id":23,"name":"Video Clips"},{"id":15,"name":"Deleted Scenes"},{"id":9,"name":"Music Albums"},{"id":7,"name":"Trailers"},{"id":18,"name":"Short Films"},{"id":21,"name":"Movie Clips"},{"id":1,"name":"Movies "},{"id":4,"name":"Plays"},{"id":22,"name":"Scenes"},{"id":2,"name":"TV Show"},{"id":5,"name":"Kids"},{"id":16,"name":"Interviews"},{"id":11,"name":"Film Songs"},{"id":14,"name":"Making of Movie"}]
I have to deserialize it how should I do this? please help
The JSON you have there represents an array of objects which look like Videos so first you will need to define a class to store each video like so:
public class Video
{
public int ID { get; set; }
public string Name { get; set; }
}
With this done you can make use of one of the many JSON libraries either built in or third party. For this example I have made use of JSON.NET. Here is a link to the documentation.
Next you will need to make use of the DeserializeObject static generic method of the JsonConvert class like so, specifying the List<Video> type so that it knows the JSON to be de-serialized is a collection of Video objects:
using Newtonsoft.Json;
...
string json = "[{\"id\":23,\"name\":\"Video Clips\"},{\"id\":15,\"name\":\"Deleted Scenes\"},{\"id\":9,\"name\":\"Music Albums\"},{\"id\":7,\"name\":\"Trailers\"},{\"id\":18,\"name\":\"Short Films\"},{\"id\":21,\"name\":\"Movie Clips\"},{\"id\":1,\"name\":\"Movies \"},{\"id\":4,\"name\":\"Plays\"},{\"id\":22,\"name\":\"Scenes\"},{\"id\":2,\"name\":\"TV Show\"},{\"id\":5,\"name\":\"Kids\"},{\"id\":16,\"name\":\"Interviews\"},{\"id\":11,\"name\":\"Film Songs\"},{\"id\":14,\"name\":\"Making of Movie\"}]";
List<Video> videos = JsonConvert.DeserializeObject<List<Video>>(json);
With this done you have a collection of Video objects to work with.
Hope this helps you.
You can deserialize the json using JavaScriptSerializer from the System.Web.Extensions dll which can be found in:
C:\Program Files\Reference
Assemblies\Microsoft\Framework.NETFramework\v4.0\System.Web.Extensions.dll
After adding a reference to the DLL in the project add:
using System.Web.Script.Serialization;
And you will also need to set Target Framework to a non-Client Profile, for example:
.NET Framework 4
Then use code like this one to deserialize the json:
var json = #"[{""id"":23,""name"":""Video Clips""},{""id"":15,""name"":""Deleted Scenes""},{""id"":9,""name"":""Music Albums""},{""id"":7,""name"":""Trailers""},{""id"":18,""name"":""Short Films""},{""id"":21,""name"":""Movie Clips""},{""id"":1,""name"":""Movies ""},{""id"":4,""name"":""Plays""},{""id"":22,""name"":""Scenes""},{""id"":2,""name"":""TV Show""},{""id"":5,""name"":""Kids""},{""id"":16,""name"":""Interviews""},{""id"":11,""name"":""Film Songs""},{""id"":14,""name"":""Making of Movie""}]";
var jsonSerializer = new JavaScriptSerializer();
var deserializedList = jsonSerializer.Deserialize<List<JsonType>>(json);
Related
I have problem with JsonConvert deserializer. I have class
[BsonCollection("matches")]
public class MatchData : Document
{
[JsonPropertyName("id")]
public string ExternalMatchId { get; set; }
...
}
In my controller, I am trying to deserialize in this way:
[HttpPost("end")]
public ActionResult RoundEnd([FromBody] dynamic data)
{
var saveData = JsonConvert.DeserializeObject<MatchData>(data.ToString());
...
}
Input JSON looks like
"{"id": "61696f268c7b70b5f3e85803",
"game_server_id": "615ed4a1cd95e8209a4ab67d",
...
But in my output MatchData object ExternalMatchId is null. How to fix that?
You are mixing frameworks here. The JsonPropertyName attribute is for the System.Text.Json namespace whereas you are using JSON.Net to deserialise. So the solution is to stick with one of them. Either deserialise with the built in framework:
System.Text.Json.JsonSerializer.Deserialize<MatchData>(data.ToString());
Or switch the attributes to use the JSON.Net versions:
[JsonProperty("Foo")]
Having said all that, it looks like you can simplify the whole thing by getting MVC to do the work for you. Instead of using dynamic as the model (don't do that - dynamic is problematic and every time you use it a kitten dies), put the model in here directly:
public ActionResult RoundEnd([FromBody] MatchData data)
i am working with json.net to deserialize json -> C# objects.
it works great in most cases but there are times where rather than getting an array i get object.
so my class (generated using http://json2csharp.com/ and modified to add property).
where i more than 1 arrival methods (such as pick up or ship) it works fine.
public class ArrivalMethods
{
[JsonProperty(PropertyName = "ArrivalMethod")]
public List<string> ArrivalMethod { get; set; }
}
but it breaks where there only 1 arrival method in the json response from my service because i believe json.net is expecting an object like below.
public class ArrivalMethods
{
[JsonProperty(PropertyName = "ArrivalMethod")]
public string ArrivalMethod { get; set; }
}
i am new to json etc. so i am not sure what i am doing wrong. but this throws exception.
Error converting value \"Ship\" to type 'System.Collections.Generic.List`1[System.String]'.
Path 'ProductDetail.SoftHardProductDetails.Fulfillment.
ArrivalMethods.ArrivalMethod', line 1, position 113."
here is where it breaks:
"ArrivalMethods":{
"ArrivalMethod":"Ship"
},
Your JSON should contain [] where there is a list. And if I'm understanding your answer correct, the first class example is the way you want to end up? If so you need the JSON on the bottom to mark ArrivalMethod as a list, wich its not now.
"ArrivalMethods":
{
"ArrivalMethod":["Ship"]
},
To be honest i get a little confused when there is a list with no plural ending.
If you can change the response format that would be the best. It really looks like XML semantics converted to JSON...
If you can't change the response format, you can try to use JsonConverterAttribute to create custom converters for those properties.
I am trying to move my website from XML based config files to JSON based ones. Is there a way to load in a .json file in so that it turns into the object? I have been searching the web and I cannot find one. I already have the .xml file converted and saved as a .json. I would rather not use a 3rd party library.
You really should use an established library, such as Newtonsoft.Json (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.
Here's a sample of reading JSON using Newtonsoft.Json:
JObject o1 = JObject.Parse(File.ReadAllText(#"c:\videogames.json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(#"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject) JToken.ReadFrom(reader);
}
Another good way to serialize json into c# is below:
RootObject ro = new RootObject();
try
{
StreamReader sr = new StreamReader(FileLoc);
string jsonString = sr.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
ro = ser.Deserialize<RootObject>(jsonString);
}
you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client
As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;
JsonSerializer serializer = new JsonSerializer();
MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(#".\path\to\json\config\file.json");
The above code assumes that you have something like
public class MyObject
{
public string prop1 { get; set; };
public string prop2 { get; set; };
}
And your json looks like;
{
"prop1":"value1",
"prop2":"value2"
}
I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.
Use Server.MapPath to get the actual path of the JSON file and load and read the file using StreamReader
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class RootObject
{
public string url_short { get; set; }
public string url_long { get; set; }
public int type { get; set; }
}
public class Program
{
static public void Main()
{
using (StreamReader r = new StreamReader(Server.MapPath("~/test.json")))
{
string json = r.ReadToEnd();
List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json);
}
Console.WriteLine(ro[0].url_short);
}
}
Note : Look below link also I have answered for question similar to this.It will be help full for you
How to Parse an example string in C#
I have done it like:
using (StreamReader sr = File.OpenText(jsonFilePath))
{
var myObject = JsonConvert.DeserializeObject<List<YourObject>>(sr.ReadToEnd());
}
also, you can do this with async call like: sr.ReadToEndAsync().
using Newtonsoft.Json as reference.
Hope, this helps.
See Microsofts JavaScriptSerializer
The JavaScriptSerializer class is used internally by the asynchronous
communication layer to serialize and deserialize the data that is
passed between the browser and the Web server. You cannot access that
instance of the serializer. However, this class exposes a public API.
Therefore, you can use the class when you want to work with JavaScript
Object Notation (JSON) in managed code.
Namespace: System.Web.Script.Serialization
Assembly: System.Web.Extensions (in System.Web.Extensions.dll)
What is the most painless way to deserialize this JSON in C# using JSON.NET?
{
"serNo":{
"A4":{
"vol":[["0","100","0,1"],["0","n","0"]],
"fix":"900"
},
"A3":{
"vol":[["0","200","0,5"],["0","n","0"]],
"fix":"700"
}
}
}
To create a separate class or as collection?
EDIT: There will be multiple "serNo" properties.
In my opinion, the most painless way to deserialize any JSON is to use the JSON.NET library. See also http://json.codeplex.com.
EDIT: Also see this other question on Stack Overflow: How to deserialize with JSON.NET?
You can use the build in lightweight JavaScriptSerializer. No attributes are required on the classes you want to serialize/deserialize.
It can also handle anonymous types.
Serialization:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var objectAsJsonString = serializer.Serialize(objectToSerialize);
Deserialization:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SomeClass deserializedObject = serializer.Deserialize<SomeClass>(objectToDeserialize);
Here is the link to an earlier related question/answer:
Error converting JSON to .Net object in asp.net
OK, I solved the problem with JSON.NET by creating this class:
class Counter
{
public double[][] vol { get; set; }
public double fix { get; set; }
}
and
deserialized JSON with this expression:
Dictionary<string, Dictionary<string, Counter>> counters = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Counter>>>(arg.Args[7]);
Where arg.Args[7] is JSON.
Check out the C# section at json.org
See Darin's answer.
I think you easily modify provided source code to match your needs. This is built-in to the .NET framework (System.Web.Script.Serialization), so there are no external dependencies.
Im working with a WCF in which i return JSON. But i get messages looking like
"{\"ids\":[\"id\":1,\"id\":34,\"id\":67,\"id\":100,\"id\":133,\"id\":166,\"id\":199]}"
How do I get rid of the first and last qoutation marks?
EDIT:
public class Ids {
public IdDetails[] ids{get;set}
}
public class IdDetails{
public int id {get;set}
}
And here I return JSON
public string GetIds(){
Ids ids = new Ids();
List<IdDetails> idd = new List<IdDetails>();
for(int i=0;i<10; i++){
idd.add(new IdDetails(i+1*33));
}
ids.ids = idd.ToArray();
JavaScriptSerializer jSerialize = new JavaScriptSerializer();
string json = jSerialize.Serialize(ids);
return ids;
}
*EDIT 2: SOLVED *
The method shouldn't return a string. It should return a Ids-object. No need to serialize.
Set the ResponseFormat = WebMassageFormat.Json and it will work.
Thanks anyways!
Are you looking with the Visual Studio Debugger at the string?
The debugger shows strings as C# string literal. The string itself doesn't actually contain the leading and trailing " characters and the \ characters.
Console.WriteLine(s);
Output:
{"ids":["id":1,"id":34,"id":67,"id":100,"id":133,"id":166,"id":199]}
JavaScriptSerializer Class
The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.
To serialize an object, use the Serialize method. To deserialize a JSON string, use the Deserialize or DeserializeObject methods. To serialize and deserialize types that are not natively supported by JavaScriptSerializer, implement custom converters by using the JavaScriptConverter class. Then register the converters by using the RegisterConverters method.
I've used it in non-web applications.