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"}]}
Related
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}");
}
I am learning how to work with json data using Newtonsoft.Json.
I stored my valid json file in a folder in my console application and calling
a method that will process the json file.
static void Main(string[] args)
{
IEnumerable<IEnumerable<string>> result;
string pathToFile = #"C:\DevelopmentJson\ConsoleApp1\File\my_test.json";
MyReader objReader = new MyReader();
result = objReader.Export(pathToFile).ToList();
Console.WriteLine("Hello");
}
Here is the method within my class that is been called.
public IEnumerable<IEnumerable<string>> Export(string json)
{
var document = JToken.Parse(json);
var data = new List<List<string>>();
.....
return data;
}
I am beginning to feel I cannot use a pathToFile as a path to my json file.
I started to get the error message below on this line [var document = JToken.Parse(json);]
Newtonsoft.Json.JsonReaderException:
'Unexpected character encountered while parsing value: C. Path '', line 0, position 0.'
How do I resolve this error message?
The Newtonsoft Json.NET documentation has two examples showing how to deserialize JSON from a file. Below are both examples with minor modifications to help integrate with your code.
Option 1. Reading JSON data via JsonConvert
var pathToFile = #"C:\DevelopmentJson\ConsoleApp1\File\my_test.json";
// read file into a string and deserialize JSON to a type
var dataFromJsonConvert = JsonConvert.DeserializeObject<MyData>(File.ReadAllText(pathToFile));
// dataFromJsonConvert now holds your JSON data from file
Option 2. Reading JSON data via JsonSerializer
var pathToFile = #"C:\DevelopmentJson\ConsoleApp1\File\my_test.json";
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(pathToFile))
{
var serializer = new JsonSerializer();
var dataFromJsonSerializer = (IEnumerable<IEnumerable<string>>)serializer.Deserialize(file, typeof(MyData));
// dataFromJsonSerializer now holds your JSON data from file
}
Example demonstrating how to utilize answer
static void Main(string[] args)
{
var pathToFile = "C:\DevelopmentJson\ConsoleApp1\File\my_test.json";
var fileJsonRaw = File.ReadAllText(pathToFile))
var objReader = new MyReader();
var fileJsonParsed = objReader.Export(fileJsonRaw).ToList();
Console.WriteLine("Hello");
}
public MyData Export(string json)
{
return JsonConvert.DeserializeObject<MyData>(json);
}
Classes generated from your JSON data
The classes below were generated from your sample JSON. These classes are used within answer to demonstrate a complete solution.
public partial class MyData
{
[JsonProperty("UpdatedDay")]
public string UpdatedDay { get; set; }
[JsonProperty("UpdatedUser")]
public string UpdatedUser { get; set; }
[JsonProperty("solution")]
public Solution[] Solution { get; set; }
}
public partial class Solution
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("fields")]
public Field[] Fields { get; set; }
}
public partial class Field
{
[JsonProperty("firstname")]
public string Firstname { get; set; }
[JsonProperty("lastiname", NullValueHandling = NullValueHandling.Ignore)]
public string Lastiname { get; set; }
[JsonProperty("required")]
public bool FieldRequired { get; set; }
[JsonProperty("lastname", NullValueHandling = NullValueHandling.Ignore)]
public string Lastname { get; set; }
}
Note: The following using statements are necessary.
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
JToken.Parse doesn't take a path, it takes the actual json string.
You can get the contents of the file with File.ReadAllText.
Something like this (checks etc omitted):
public IEnumerable<IEnumerable<string>> Export(string path)
{
string json = File.ReadAllText(path);
var document = JToken.Parse(json);
var data = new List<List<string>>();
.....
return data;
}
Note that there are better ways of parsing a file with json.net. For more info read this.
SO I have a Json array as following:
{[data, [{"name":"Micheal Jackson","pic_large":"https://scontent.x.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938","id":"10154729171332597"}
How can I serialize it with C# to parse it into objects and then pass it to the view.
EDIT:
{[data, [{"name":"Sayed Zubair Hashimi","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938","id":"10154729171332597"},{"name":"Junaid Walizada","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14055012_1760562554217155_4937121194048198140_n.jpg?oh=376b49c9d04c2676ebe3d853b122165e&oe=58EA033D","id":"1821833754756701"},{"name":"Mohib Akhondzada","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/s200x200/14264218_592094647641140_6351146344336469735_n.jpg?oh=a8a63893d71f76c45fa3d07389f1700a&oe=59147C84","id":"648198542030750"},{"name":"Za Beah","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15741112_359701871054520_6692094260041596196_n.jpg?oh=6d9a0e73f70145b821c79cbe738090a0&oe=58E5B5B5","id":"360411140983593"},{"name":"Baser Nader","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15094436_10153876544626432_1550234361821853528_n.jpg?oh=e197fa712b3180a20612ecdacb01747c&oe=58E54DEC","id":"10153975726331432"},{"name":"Abasin Deniz","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15698075_440749809647293_7905213567074684088_n.jpg?oh=aeb22664f458d75fc00638ca6fa4ecfc&oe=591F7BB3","id":"444098429312431"}]]}
EDIT2:
Here is how I retrieve above Json.
var appsecret_proof = access_token.GenerateAppSecretProof();
var fb = new FacebookClient(access_token);
dynamic myFeed = await fb.GetTaskAsync(
("me/feed?fields=likes{{name,pic_large}}")
.GraphAPICall(appsecret_proof));
The strings shown in your question are all invalid JSON. A properly formatted JSON might look like this:
{
"data": [{
"name": "Micheal Jackson",
"pic_large": "https://scontent.x.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938",
"id": "10154729171332597"
}]
}
Now if you want to map this to C# class that's pretty easy to do. Just define the models to reflect this structure:
public class Feed
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("pic_large")]
public string PicLarge { get; set; }
}
public class Result
{
[JsonProperty("data")]
public IList<Feed> Feeds { get; set; }
}
and then all that's left is to deserialize the JSON string using a JSON serializer such as Json.NET back to this object structure:
string json = ... the json string shown above
var result = JsonConvert.DeserializeObject<Result>(json);
foreach (var feed in result.Feeds)
{
Console.WriteLine(feed.Name);
}
first you need to create class with properties same as in json and then use the following code :
class obj
{
public string name {get ; set; }
public string pic_large {get ; set; }
public id {get ; set; }
}
using System.Web.Script.Serialization;
.
.
var obj = new JavaScriptSerializer().Deserialize<obj>(jsonString);
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);
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"}]}