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.
Related
This question already has answers here:
Deserialize JSON with C#
(10 answers)
Closed 1 year ago.
{
"status": "success",
"data": {
"custid1": 723,
"custid2": 670,
"custid3": 430
}
}
It doesn't have key-value pair it just contains the value of two columns. I have tried it by converting it into a data table but not getting the required result.
You can create a class like below. and then use NewtonSoft to deserialize it to the class object.
public class Data
{
public int custid1 { get; set; }
public int custid2 { get; set; }
public int custid3 { get; set; }
}
public class Example
{
public string status { get; set; }
public Data data { get; set; }
}
Code to deserialize:
string json = <yourjson>;
Example ex = JsonConvert.DeserializeObject<Example>(json);
You can see the nugget package details here.
You can deserialize it to ExpandoObject
ExpandoObject object1 = JsonConvert.DeserializeObject<ExpandoObject>(json);
{
"user": {
"id": 121,
"username": "luckygirl3",
"counter_rechecking": 0,
"user_id": 76,
"f_Id": "4334"
}
}
How to convert it to object and post it to api. I have already know how to post but I need to post user object with parameters. I tried this:
JObject jobjects = new JObject();
JObject jobjectss = new JObject();
jobjects["user"] = jobjectss;
jobjectss["id"] = 121;
jobjectss["username"] = "luckygirlx3";
jobjectss["counter_rechecking"] = 0;
jobjectss["user_id"] = 76;
jobjectss["f_Id"] = "4334";
How to Convert Json to object c# To Post Data APi
This seems like you want to convert a JSON response to a object. If this is the case then you want to deserialize your JSON. You havn't posted your Post Data code, so I can't help much with that.
I would first map your JSON to classes:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
[JsonProperty("counter_rechecking")]
public int CounterRechecking { get; set; }
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("f_id")]
public string FId { get; set; }
}
public class RootObject
{
public User User { get; set; }
}
Then deserialize your JSON to RootObject with Json.NET:
var deserializedJson = JsonConvert.DeserializeObject<RootObject>(json);
You can then access your properties like this:
Console.WriteLine(deserializedJson.User.Id);
Console.WriteLine(deserializedJson.User.Username);
Console.WriteLine(deserializedJson.User.CounterRechecking);
Console.WriteLine(deserializedJson.User.UserId);
Console.WriteLine(deserializedJson.User.FId);
I used JsonProperty to map your attributes with _ to nicer property members. This is optional however.
You can also use something like json2csharp.com or Edit -> Paste Sepcial -> Paste JSON as classes inside Visual Studio after copying your JSON to the clipboard to generate the classes for you.
Full demo at dotnetfiddle.net.
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
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>.
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);