I am a beginner in .Net framework, and I want to know how I can return a model without matching all the parameters in the json data. For example I have an unknown json coming in but I do know that there will be a "Name" and "Nickname" value, so I want to create an object model from these values.
Is this what you mean?
public class MyClass
{
public string key { get; set; }
public NameArray[] array { get; set; }
}
public class NameArray
{
public string Name { get; set; }
}
static void Main(string[] args)
{
string jsonString = "{\"key\": \"myKey\", \"array\": [{\"Name\": \"John\"},{\"Name\": \"Jack\"}]}";
var myClass = JsonSerializer.Deserialize<MyClass>(jsonString);
Console.WriteLine($"key: {myClass.key}");
Console.WriteLine($"name0: {myClass.array[0].Name}");
Console.WriteLine($"name1: {myClass.array[1].Name}");
}
You need a class that has your values and that's what JsonSerializer will use to deserialize the json string.
public class MyClass
{
public string Name { get; set; }
public string Nickname { get; set; }
}
static void Main(string[] args)
{
string jsonString = "{\"firstName\": \"ABC\", \"lastName\": \"XYZ\", \"age\": 5, \"email\":\"abcxyz #blahblah.com\", \"Name\": \"ABC XYZ\", \"Nickname\": \"AZ\"}";
var myClass = JsonSerializer.Deserialize<MyClass>(jsonString);
Console.WriteLine($"Name: {myClass.Name}");
Console.WriteLine($"Nickname: {myClass.Nickname}");
}
Json string:
{"movies":[{"id":"1","title":"Sherlock"},{"id":"2","title":"The Matrix"}]}
C# class:
public class Movie {
public string title { get; set; }
}
C# converting json to c# list of Movie's:
JavaScriptSerializer jss = new JavaScriptSerializer();
List<Movie> movies = jss.Deserialize<List<Movie>>(jsonString);
My movies variable is ending up being an empty list with count = 0. Am I missing something?
Your c# class mapping doesn't match with json structure.
Solution :
class MovieCollection {
public IEnumerable<Movie> movies { get; set; }
}
class Movie {
public string title { get; set; }
}
class Program {
static void Main(string[] args)
{
string jsonString = #"{""movies"":[{""id"":""1"",""title"":""Sherlock""},{""id"":""2"",""title"":""The Matrix""}]}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
MovieCollection collection = serializer.Deserialize<MovieCollection>(jsonString);
}
}
If you want to match the C# structure, you can change the JSON string like this:
{[{"id":"1","title":"Sherlock"},{"id":"2","title":"The Matrix"}]}
when I trying to serialize to json an regular class that i read before all the properties in the json starts with $.
Why and how can I resolve it
Your question does not have enough details, perhaps the below will help with going from a C# class to a JSON object and back.
First Create a class that mimics your JSON string (object) structure:
public class JSONobject
{
public Foo = new Foo();
}
public class Foo
{
public string First { get; set; }
public string Last {get;set;}
public int ID {get;set;}
........
........
public Bar = new Cover();
}
public class Bar
{
public int ID{ get;set; }
........
}
Then, initialize the object as well as the serializer:
JSONobject jsonOb = new JSONobject();
JavaScriptSerializer serializer = new JavaScriptSerializer();
Finally, parse the jsonString into your defined class:
try
{
jsonOb = serializer.Deserialize<JSONobject>(jsonString);
//ViewBag.jsondecoded = "Yes";
}
catch (Exception e)
{
//ViewBag.jsonDecoded = "No" + ", Exception: " + e.Message.ToString();
}
The object now has all the data from your JSON object.
At last, you can do this backwards, just serialize the object:
string json = JsonConvert.SerializeObject(jsonOb);
I am trying for many hours to parse a JsonArray, I have got by graph.facebook, so that i can extra values. The values I want to extract are message and ID.
Getting the JasonArry is no Problem and works fine:
[
{
"code":200,
"headers":[{"name":"Access-Control-Allow-Origin","value":"*"}],
"body":"{
\"id\":\"255572697884115_1\",
\"from\":{
\"name\":\"xyzk\",
\"id\":\"59788447049\"},
\"message\":\"This is the first message\",
\"created_time\":\"2011-11-04T21:32:50+0000\"}"},
{
"code":200,
"headers":[{"name":"Access-Control-Allow-Origin","value":"*"}],
"body":"{
\"id\":\"255572697884115_2\",
\"from\":{
\"name\":\"xyzk\",
\"id\":\"59788447049\"},
\"message\":\"This is the second message\",
\"created_time\":\"2012-01-03T21:05:59+0000\"}"}
]
Now I have tried several methods to get access to message, but every method ends in catch... and throws an exception.
For example:
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
foreach (var item in result)
{
Console.WriteLine(item.body.message);
}
throws the exception: System.Collections.Generic.Dictionary doesnt contain definitions for body. Nevertheless you see in the screenshot below, that body contains definitions.
Becaus I am not allowed to post pictures you can find it on directupload: http://s7.directupload.net/images/120907/zh5xyy2k.png
I don't havent more ideas so i please you to help me. I need this for a project, private, not commercial.
Maybe you could give me an phrase of code, so i can continue my development.
Thank you so far
Dominic
If you use Json.Net, All you have to do is
replacing
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
with
dynamic result = JsonConvert.DeserializeObject(json);
that's all.
You are not deserializing to a strongly typed object so it's normal that the applications throws an exception. In other words, the deserializer won't create an Anynymous class for you.
Your string is actually deserialized to 2 objects, each containing Dictionary<string,object> elements. So what you need to do is this:
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(s);
foreach(var item in result)
{
Console.WriteLine(item["body"]["message"]);
}
Here's a complete sample code:
void Main()
{
string json = #"[
{
""code"":200,
""headers"":[{""name"":""Access-Control-Allow-Origin"",""value"":""*""}],
""body"":{
""id"":""255572697884115_1"",
""from"":{
""name"":""xyzk"",
""id"":""59788447049""},
""message"":""This is the first message"",
""created_time"":""2011-11-04T21:32:50+0000""}},
{
""code"":200,
""headers"":[{""name"":""Access-Control-Allow-Origin"",""value"":""*""}],
""body"":{
""id"":""255572697884115_2"",
""from"":{
""name"":""xyzk"",
""id"":""59788447049""},
""message"":""This is the second message"",
""created_time"":""2012-01-03T21:05:59+0000""}}
]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
foreach(var item in result)
{
Console.WriteLine(item["body"]["message"]);
}
}
Prints:
This is the first message
This is the second message
I am using this simple technique
var responseTextFacebook =
#"{
"id":"100000891948867",
"name":"Nishant Sharma",
"first_name":"Nishant",
"last_name":"Sharma",
"link":"https:\/\/www.facebook.com\/profile.php?id=100000891948867",
"gender":"male",
"email":"nihantanu2010\u0040gmail.com",
"timezone":5.5,
"locale":"en_US",
"verified":true,
"updated_time":"2013-06-10T07:56:39+0000"
}"
I have declared a class
public class RootObject
{
public string id { get; set; }
public string name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string link { get; set; }
public string gender { get; set; }
public string email { get; set; }
public double timezone { get; set; }
public string locale { get; set; }
public bool verified { get; set; }
public string updated_time { get; set; }
}
Now I am deserializing
JavaScriptSerializer objJavaScriptSerializer = new JavaScriptSerializer();
RootObject parsedData = objJavaScriptSerializer.Deserialize<RootObject>(responseTextFacebook );
Wondering how to deserialize the following string in c#:
"[{\"access_token\":\"thisistheaccesstoken\"}]"
I know how to do it if the json was:
"{array=[{\"access_token\":\"thisistheaccesstoken\"}]}"
I'd do it like this:
public class AccessToken
{
public string access_token {get;set;}
public DateTime expires { get; set; }
}
public class TokenReturn
{
public List<AccessToken> tokens { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
TokenReturn result = ser.Deserialize<TokenReturn>(responseFromServer);
But without that array name, I'm not sure. Any suggestions?
Thanks!
Never mind, Just did it with:
JavaScriptSerializer ser = new JavaScriptSerializer();
List<AccessToken> result = ser.Deserialize<List<AccessToken>>(jsonString);