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);
Related
I don't want to use Newtonsoft's Json.Net library. I'm avoiding any third-party dependencies if I can help it in this project.
If I have JSON that looks like this:
{
"has_more_items": false,
"items_html": "...",
"min_position": "1029839231781429248"
}
and I have a class that looks like this:
public class TwitterJson
{
bool hasMore { get; set; } // has_more_items
string rawText { get; set; } // items_html
string nextKey { get; set; } // min_position
}
and I have a JsonObject containing the above JSON:
JsonObject theJson = JsonObject.Parse(result);
How do I deserialize the JsonObject into my class? I've been trying to find a clear example of this, and everything I've found uses Json.Net.
I've been trying to find a clear example of this, and everything I've found uses Json.Net.
Because reinventing existing functionality is a waste of time especially when all the hard work has already been done for you.
If you insist on not using it then you will have to manually construct the object model based on the expected JSON.
For example, assuming publicly available properties
public class TwitterJson {
public bool hasMore { get; set; } // has_more_items
public string rawText { get; set; } // items_html
public string nextKey { get; set; } // min_position
}
Then parsing the above to the desired object model
JsonObject theJson = JsonObject.Parse(result);
var model = new TwitterJson {
hasMore = theJson.GetNamedBoolean("has_more_items"),
rawText = theJson.GetNamedString("items_html"),
nextKey = theJson.GetNamedString("min_position")
};
As mentioned by #Dimith, you need to decorate your class with [DataContract] and [DateMember], Please refer to below code which will convert your JSON into a given object.
// Deserialize a JSON string to a given object.
public static T ReadToObject<T>(string json) where T: class, new()
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return ser.ReadObject(stream) as T;
}
}
Class:
[DataContract]
public class TwitterJson
{
[DataMember(Name = "has_more_items")]
bool hasMore { get; set; } // has_more_items
[DataMember(Name = "items_html")]
string rawText { get; set; } // items_html
[DataMember(Name = "min_position")]
string nextKey { get; set; } // min_position
}
Sample on how to use:
var result = "{\"has_more_items\": false, \"items_html\": \"...\",\"min_position\": \"1029839231781429248\"}";
var obj = ReadToObject<TwitterJson>(result);
You have to decorate your class with [DataContract] and [DataMember] attributes. Write the json into a memory stream and deserialize using DataContractJsonSerializer
Here is a more elaborated sample.
In addition to #Nkosi's answer below are some Comparisons between JSON.net and other alternatives:
JSON.Net vs DataContractJsonSerializer
JSON.Net vs Windows.Data.Json
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"}]}
I am trying to post some data to my MVC 3 controller through a hidden text field that contains some JSON. I have that JSON passed in via string coursesList. Anyone have an idea why this is not working?
All I'm doing is making a byte [] out of the JSON string, writing it to a MemoryStream, and deserializing that stream -- or, attempting to. BookCourse bc always ends up with null properties.
Here's something like the JSON I would be using:
[{"coursesection":"1234","netlogon":"jsmith","label":"CRSE-1313 Generic Course Titling ~ Joe Smith"}]
And here's the object to be deserialized into:
using System.Runtime.Serialization;
namespace xxxx.Models
{
[DataContract]
public class BookCourse
{
[DataMember]
public string coursesection { get; set; }
[DataMember]
public string netlogon { get; set; }
[DataMember]
public string label { get; set; }
}
}
Finally, the controller action code to do it --
var byteArray = Encoding.ASCII.GetBytes(coursesList);
// Deserialize byte array to data type
var stream = new MemoryStream();
stream.Write(byteArray, 0, byteArray.Length);
var crs = new DataContractJsonSerializer(typeof(BookCourse));
stream.Position = 0;
// Read stream to object
ad.CourseSectionIDs = new List<int>();
try
{
var bc = (BookCourse) crs.ReadObject(stream);
while (bc.coursesection != null)
{
cs.AssociateCourseBook(bc.netlogon, bc.coursesection, ad.ISBN);
bc = (BookCourse)crs.ReadObject(stream);
}
}
catch (System.Runtime.Serialization.SerializationException e)
{
// Is this best practice for handling "none"?
}
Your JSON string represents a collection of BookCourse, not a single BookCourse. So adapt your code:
var serializer = new DataContractJsonSerializer(typeof(BookCourse[]));
and then:
var bookCourses = (BookCourse[])crs.ReadObject(stream);
or if you want to work with a single BookCourse you will need to change your JSON string and remove the wrapping square brackets which represent a collection.
Darin is correct, here is the change if you want to do it on a contract level.
[DataContract]
public class BookCourse
{
[DataMember]
public string coursesection { get; set; }
[DataMember]
public string netlogon { get; set; }
[DataMember]
public string label { get; set; }
}
[DataContract]
public class BookCourceCollection
{
[DataMember]
public List<BookCourse> Collection;
public static BookCourceCollection ReturnCollection(string jsonString)
{
MemoryStream ms;
BookCourceCollection collection;
using (ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BookCourceCollection));
collection = ser.ReadObject(ms) as BookCourceCollection;
}
return collection;
}
}
Usage:
string jsonString = "Your JSON string from the front end";
var bookCourceObject = BookCourseCollection.ReturnCollection(jsonString);
foreach (BookCourse bookCourse in bookCourceObject.Collection)
{
cs.AssociateCourseBook(bookCourse.netlogon, bookCourse.coursesection, bookCourse.ISBN);
}
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"}]}
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);