Convert object to JSON string in C# [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Turn C# object into a JSON string in .NET 4
In the Java, I have a code to convert java object to JSON string. How to do the similar in the C# ? which JSON library I should use ?
Thanks.
JAVA code
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class ReturnData {
int total;
List<ExceptionReport> exceptionReportList;
public String getJSon(){
JSONObject json = new JSONObject();
json.put("totalCount", total);
JSONArray jsonArray = new JSONArray();
for(ExceptionReport report : exceptionReportList){
JSONObject jsonTmp = new JSONObject();
jsonTmp.put("reportId", report.getReportId());
jsonTmp.put("message", report.getMessage());
jsonArray.add(jsonTmp);
}
json.put("reports", jsonArray);
return json.toString();
}
...
}

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.
public class ReturnData
{
public int totalCount { get; set; }
public List<ExceptionReport> reports { get; set; }
}
public class ExceptionReport
{
public int reportId { get; set; }
public string message { get; set; }
}
string json = JsonConvert.SerializeObject(myReturnData);

Use .net inbuilt class JavaScriptSerializer
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(obj);

Related

UWP C# - How to deserialize JsonObject into a class using Windows.Data.Json?

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 convert to c# using newtonsoft [duplicate]

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"}]}

how to read the json object data in c#? [duplicate]

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.

Json string deserialized to array list of objects

Please help!
Getting this error on Deserializing:
Cannot convert object of type 'System.String' to type
'System.Collections.Generic.List'
JSON string from client:
"\"[{\\"id\\":\\"18_0_2_0\\",\\"ans\\":\\"You can enter free
text in place of
*\\"},{\\"id\\":\\"23_1_3_1\\",\\"ans\\":\\"The refresh button\\"},{\\"id\\":\\"11_2_1_2\\",\\"ans\\":\\"False\\"}]\""
Edit: Unescaped (see comments):
[{"id":"18_0_2_0","ans":"You can enter free text in place of *"},{"id":"11_2_1_2","ans":"False"}]
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<RawAnswer> ListAnswers = serializer.Deserialize<List<RawAnswer>>(str);
[Serializable]
public class RawAnswer
{
public string QuestionID { get; set; }
public string Answer { get; set; }
public RawAnswer() { }
}
public class AnswerList
{
public List<RawAnswer> RawAnswer { get; set; }
}
Your original json string(before aKzenT's edit) was double escaped and I used var str2 = Regex.Unescape(str); to get the actual string .
public class RawAnswer
{
public string id { get; set; }
public string ans { get; set; }
}
And no need for AnswerList
Now your code can work
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<RawAnswer> ListAnswers = serializer.Deserialize<List<RawAnswer>>(str);
The JSON string you receive from the client is itself a string containing the actual JSON string you're looking for. Either fix the client to send you a correct string, or first deserialize this result into a String, and then deserialize that into a List<RawAnswer>.

How can I convert JSON to DataTable using C#

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.

Categories

Resources