I have a json string and would like to make a DataTable from it.
How can I convert JSON to a DataTable in C#?
Update:
I have used Json.Net as per link provided here
and build 2 class to to handle json string as per below
public class JsonHelper
{
public List<User> userdata { get; set; }
}
public class User
{
public string name { get; set; }
public string id { get; set; }
public DateTime createdDate { get; set; }
}
and use following code to Deserialize
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
StringReader sr = new StringReader(jsonstr);
Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
object result = json.Deserialize(reader, typeof( JsonHelper));
reader.Close();
return result;
but getting following error
Cannot deserialize JSON array into type 'mynamespace+JsonHelper'.
What should be problem here , please help me to sort out this problem.
thanks.
This post by Rick Strahl may help you out. Under the covers he's using Newtonsoft's JSON.NET libraries to do the heavy lifting.
Related
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.
maybe this was asked somewhere before, but I don't know how to search for my problem.
I'm using a WebAPI to verify licenses. From this API I get the return JSON string in follwing format.
string json = "[{"status":"error","status_code":"e002","message":"Invalid licence key"}]"
This is my serializer
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ActivationResponseWooSl));
ActivationResponseWooSl ar = (ActivationResponseWooSl)js.ReadObject(ms);
}
Now my questions is, how must the "ActivationResponseWooSl" class look like so that the serializer can convert it?
Any help is highly appreciated!
For now it looks like that (what's not workiing):
[DataContract]
public class ActivationResponseWooSl
{
[DataMember(Name = "status")]
public string Status { get; set; }
[DataMember(Name = "status_code")]
public string ErrorCode { get; set; }
[DataMember(Name = "message")]
public string ErrorMessage { get; set; }
}
However when I serialize my json string, all properties are "null".
Your class is correct. Your JSON is an array of object.
Try
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ActivationResponseWooSl[]));
var arr = (ActivationResponseWooSl[])js.ReadObject(ms);
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
This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 7 years ago.
I have the json String
{
"isSuccess": true,
"responseMessage": "Voucher Code is valid!",
"responseData": {
"vouchername": "COMPANY",
"vouchercode": "sss12",
"vouchervalue": "100"
}
}
How can i read this JSON data in c# code?
Use JsonConvert.DeserializeObject() to deserialize this string into a Class Type then simply access its properties in the usual way.
public class Rootobject
{
public bool isSuccess { get; set; }
public string responseMessage { get; set; }
public Responsedata responseData { get; set; }
}
public class Responsedata
{
public string vouchername { get; set; }
public string vouchercode { get; set; }
public string vouchervalue { get; set; }
}
Then you can access the values like this
var results = JsonConvert.DeserializeObject<Rootobject>(json);
var strResponseMessage = results.responseMessage ;
var strVoucherName = results.responseData.vouchername;
The links provided by dbc are very helpful. Do have a look on it
You can deseralize your json data in different ways.Either make a class for json values or use a dictionary and access data from it after serialization.
For this code You need to add a reference to your project to "System.Web.Extensions.dll"
using System.Web.Script.Serialization;
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string,dynamic>>(jsonText);
You can access your desired fields as
bool isSuccess = Convert.ToBool(dict["isSuccess"]);
string vouchername = Convert.ToString(dict["responseData"]["vouchername"]);
Create c# class that can deserialize your json string. You can do it here json2csharp.com
Add newtonsoft json Nuget package to your solution.
Then you can deserialize your string like,
var requestToken =
JsonConvert.DeserializeObject<(RequestToken)>(Content);
where,
RequestToken is your C# class name and Content is your json string.
Thanks.
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 );