Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 11 months ago.
Improve this question
I am trying to save a JSON file in C# with variables from user input. I am using Visual Studio with Newtonsoft.Json. Does anyone know how to create a JSON object with variables of name, description, and code.
Assuming you are using the following class:
public class CustomClass {
public string Name { get; set; }
public string Job { get; set; }
public int Age { get; set; }
}
Saving class objects as JSON file:
var user = new CustomClass() {
Name = "John Wick",
Job = "Businessman",
Age = 42
};
var jsonString = JsonConvert.SerializeObject(user, Formatting.Indented);
File.WriteAllText(#"C:\temp\user.json", jsonString);
Loading JSON files and converting them to C# objects:
var jsonString = File.ReadAllText(#"C:\temp\user.json");
CustomClass? user = JsonConvert.DeserializeObject<CustomClass>(jsonString);
Additional:
By default, parsing will map the property names directly. Parsing the example from above to JSON would return:
{
"Name": "John Wick",
"Job": "Businessman",
"Age": 42
}
If you need to parse JSON objects, where the stored properties are different from the property names of your class, you can "rename" them by using property tags.
using Newtonsoft.Json;
public class CustomClass {
[JsonProperty("user_name")]
public string Name { get; set; }
[JsonProperty("user_job")]
public string Job { get; set; }
[JsonProperty("user_age")]
public int Age { get; set; }
}
When parsed, this will return the following output:
{
"user_name": "John Wick",
"user_job": "Businessman",
"user_age": 42
}
A sample for you:
void Main()
{
var data = new {
name ="Your Name",
description="This is my name",
code="007"
};
var json = JsonConvert.SerializeObject(data);
File.WriteAllText(#"c:\temp\myJson.json", json);
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
i have a returned string looks like this
"{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}"
i have tries to Deserialize by using dictionary but still not catching the data.
the most important data is just named inside the properties, item1, item2
System.Text.Json.JsonSerializer.Deserialize<IDictionary<string, object>>(jsonString)
and it' giving the folowing result
[0] [KeyValuePair]:{[properties, {"Item1":{"dataType":"string"},"item2":{"dataType":"string"}
Key [string]:"properties"
Value [object]:ValueKind = Object : "{"item1":{"dataType":"string"},"item2":{"dataType":"string"}
Key [string]:"lastModified"
[1] [KeyValuePair]:{[lastModified, 2021-12-09T19:00:12Z]}
You can deserialize the JSON string to an object by following these simple steps:
Create a C# class from the JSON data. To do this, copy the JSON string and go to VS, Edit, Paste Special, Paste JSON as Classes.
if successful, you will get a C# class like this one
public class Rootobject
{
public Properties properties { get; set; }
public DateTime lastModified { get; set; }
}
public class Properties
{
public Item1 item1 { get; set; }
public Item2 item2 { get; set; }
}
public class Item1
{
public string dataType { get; set; }
}
public class Item2
{
public string dataType { get; set; }
}
You can rename the classes to anything that make meaning to you.
The you can deserialize like this
var obj = JsonConvert.DeserializeObject<Rootobject>(
"{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
Console.WriteLine(obj.properties.item2.dataType)// string
If you only need the value of dataType property and not the whole object, than you can use Linq to Json to get it without deserialization and object mapping.
The examples:
var obj = JObject.Parse("{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
var fistItemDataTypeValue = (string)obj["properties"]?["item1"]["dataType"];
var secondItemDataTypeValue = (string)obj["properties"]?["item2"]["dataType"];
Getting values as list of strings (NOTES: if you already know the number of items in json):
var obj = JObject.Parse("{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
var listOfValues = new List<string>();
for (int i = 1; i <= 2; i++)
{
listOfValues.Add((string)obj["properties"]?[$"item{i}"]["dataType"]);
}
! More about linq to json
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I Want Make C# App That Shows Your Roblox Name By UserID
Here Is My Profile's Json But I Dont Know How To Get Json Data: https://api.roblox.com/users/157816362
For Example:
json = new System.Net.WebClient(){ Proxy = null }.DownloadString("https://api.roblox.com/users/157816362");
label1.text = json.Username
Something Like This.
Can You Guys/Girls Please Help Me?
Heres an example program, you have to create a web request, pass the url you want in and then get the response from that.
From there you have to 'deserialize' the response into an object that you can use in code. I used the System.Json one, but there are others like newtonsoft that you can choose from.
internal class Program
{
public static void Main(string[] args)
{
var webRequest = WebRequest.Create("https://api.roblox.com/users/157816362");
var response = webRequest.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
string body = reader.ReadToEnd();
var robloxProfile = JsonSerializer.Deserialize<RobloxResponse>(body);
}
}
}
public class RobloxResponse
{
public int Id { get; set; }
public string Username { get; set; }
public string AvatarUri { get; set; }
public bool AvatarFinal { get; set; }
public bool IsOnline { get; set; }
}
You almost have the answer. You should create a class that maps to the json, download the Newtonsoft.Json nuget and convert the string data that you get from the WebClient.DownloadString into a class through the JsonConvert class. Like this:
class Program {
static void Main(string[] args) {
using (var client = new WebClient()) {
var data = client.DownloadString("https://api.roblox.com/users/157816362");
var jsonData = JsonConvert.DeserializeObject<JsonData>(data);
Console.WriteLine($"{jsonData.Username}");
}
Console.ReadLine();
}
public class JsonData {
public int Id { get; set; }
public string Username { get; set; }
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have one JSON like:
In success response it is like:
{
statusCode: "200",
status: "Success",
data: [
{
empName: "Prashant",
empCode: 001
},
{
empName: "Jack",
empCode: 002
}
]
}
and In error response or if there is an exception while processing a request like:
{
statusCode: "400",
status: "Fail",
data: {
empId: "This field is mandatory"
}
}
How I can parse the response in both case? Now I am getting an exception while parsing the JSON.
The C# Class I used to parse the response is:
public class Employee
{
public string empName { get; set; }
public int empCode { get; set; }
}
public class Response
{
public string statusCode { get; set; }
public string status { get; set; }
public List<Employee> data { get; set; }
}
EDIT:
The exception details:
System.InvalidCastException: Specified cast is not valid.
You can use Newtonsoft.Json [https://www.newtonsoft.com/json]
When you install Newtonsoft.Json from NugetLibrary you can use code below,
String json = "{statusCode: \"200\",status: \"Success\",data: [{empName: \"Prashant\",empCode: 001},{empName: \"Jack\",empCode: 002}]}";
Response resp = JsonConvert.DeserializeObject<Response>(json);
Your normal response maps directly to classes you provided. And this is deserialized without any problem.
The problem emerges, when you try deserialize your error resopnse. It specifies empId which is not present in any of your classes. That is generating exception.
Also, in your normal response, you have list in data (indicated by square brackets [ and ]), in second, you don't have a list. This is also inconsistent and is causing exception.
In order to make it work, you have to modify your error response:
1) change empId to empName or add empId in your Employee class:
public class Employee
{
public string empId { get; set; }
public string empName { get; set; }
public int empCode { get; set; }
}
2) alter data field in JSON, so it will be an array:
{
statusCode: ""400"",
status: ""Fail"",
data: [{
empId: ""This field is mandatory""
}]
}
Finally, deserialize it with:
var normalObject = JsonConvert.DeserializeObject<Response>(normalJson);
var errorObject = JsonConvert.DeserializeObject<Response>(errorJson);
UPDATE
If you want statusCode only, make the type of data in Response class object, so it won't throw exception while parsing:
public class Response
{
public string statusCode { get; set; }
public string status { get; set; }
public object data { get; set; }
}
To get statusCode directly, use:
var statusCode = JsonConvert.DeserializeObject<Response>(normalJson).statusCode;
statusCode = JsonConvert.DeserializeObject<Response>(errorJson).statusCode;
If your objects are not fixed and data must be configurable then Newtonsoft.json has one feature that to be use here and that is [JsonExtensionData]. Read more
Extension data is now written when an object is serialized. Reading and writing extension data makes it possible to automatically round-trip all JSON without adding every property to the .NET type you’re deserializing to. Only declare the properties you’re interested in and let extension data do the rest.
So in your case your Response class will be
public class Response
{
public string statusCode { get; set; }
public string status { get; set; }
[JsonExtensionData]
public Dictionary<string, JToken> data;
}
All your data in data key will be collected in [JsonExtensionData] property.
You need to perform operations on [JsonExtensionData] property to get your key/value pair. like
public class Employee
{
public string empId { get; set; }
public string empName { get; set; }
public int empCode { get; set; }
}
And you can perform opration like
var json = "Your response";
JObject jObject = JObject.Parse(json);
var statusCode = jObject["statusCode"];
var status = jObject["status"];
var data = jObject["data"];
if (data.Type == JTokenType.Array)
{
var arrayData = data.ToObject<List<Employee>>();
}
else
if (data.Type == JTokenType.Object)
{
var objData = data.ToObject<Employee>();
}
JsonConvert.DeserializeObject<T>(variableHoldingJsonString);
where T is the type of the object/list you want the main to be.
This will give the desired result.
However there is a lot of help out there already.
I like to use the Newtonsoft package from NuGet. It works really well.
Newtonsoft.Json.JsonConvert.DeserializeObject<T>(Response);
T is the object of choice (you can special paste a JSON string to create a class if you have the web development kit active in VS2017).
The class structure has to match that of the JSON string. In the first example, a list of Employee data has empName and empCode so it will convert fine, but in the second example you haven't catered for empId so it doesn't know how to parse it.
Depending on status code you need different classes for deserialization. Use the following code to extract statusCode and deserialize string later to different object using your approach (Newtonsoft.json nuget is used):
dynamic js = JObject.Parse(str);
var code = js.statusCode;
public partial class Response
{
[JsonProperty("statusCode")]
public long StatusCode { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("data")]
public Employee[] Data { get; set; }
}
public partial class Employee
{
[JsonProperty("empName")]
public string EmpName { get; set; }
[JsonProperty("empCode")]
public long EmpCode { get; set; }
[JsonProperty("empId")]
public string EmpId { get; set; }
}
var ResponseJSON= JsonConvert.DeserializeObject<Response>(normalJson);
above class will help you to parse your json. you just need to check for Emplid is null or empty base on that you can simply do your work what you need.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How to create a JSON-Array in C# so that we can insert a variable (array of emails) for example "test#gmail;test1#gmail..." into it?
[
{
"To":[
{
"EntryType":2,
"username":"jack",
"email":"test#gmail.com"
}
],
"Cc":[
{
"EntryType":2,
"username":"mikle",
"email":"test1#gmail.com"
},
{
"EntryType":2,
"username":"jone",
"email":"test2#gmail.com"
}
],
"Bcc":[
{
"EntryType":2,
"username":"luis",
"email":"test3#gmail.com"
}
]
}
]
I used json2csharp.com to generated C# classes from your JSON. That results in this:
public class Recepient
{
public int EntryType { get; set; }
public string username { get; set; }
public string email { get; set; }
}
public class Mail
{
public List<Recepient> To { get; set; }
public List<Recepient> Cc { get; set; }
public List<Recepient> Bcc { get; set; }
}
Actually it created four other classes RootObject, To, Cc and Bcc but I renamed them to Mail and Recipient.
To create JSON from these classes, with Newtonsoft.Json, you can do this:
using Newtonsoft.Json;
public string Demo()
{
var mails = new List<Mail>();
var mail = new Mail();
mail.To = new List<Recepient>{
new Recepient
{
EntryType = 2,
username = "jack",
email = "test#gmail.com"
}
};
mail.Cc = new List<Recepient>();
mail.Bcc = new List<Recepient>();
mails.Add(mail);
return JsonConvert.SerializeObject(mails);
}
Use JSON.net and you will never look back.
http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to display a list pulled from the eztv.re API in a listbox. I have
tried using:
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(("http://eztvapi.re/shows/1&query_term=" + SearchTextBox.Text)))
{
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
{
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
var root = JsonConvert.DeserializeObject<RootObject>(json);
var articles = root.Select(m => new Article { Name = root.title, ImagePath = root.images.poster, id = root._id, Year = root.year }).ToList();
foreach (Article s in articles)
{
this.Listbox.Items.Add(new Article { Name = s.Name, ImagePath = s.ImagePath, Year = s.Year, id = s.id });
}
}
}
}
But root.select doesn't work, my RootObject class being:
public class RootObject
{
public string _id { get; set; }
public Images images { get; set; }
public string imdb_id { get; set; }
public object last_updated { get; set; }
public int num_seasons { get; set; }
public string slug { get; set; }
public string title { get; set; }
public string tvdb_id { get; set; }
public string year { get; set; }
}
the Article class is simply a list of strings. My code functions perfectly with another API (yts.to), but in that one, I use RootObject.Data, the data class containing
public List<Movie> movies { get; set; }
I know the solution to this is probably rather simple, but I can't seem to find it.
It looks like your API returns a List<RootObject>, not a single RootObject. This worked for me:
string json = reader.ReadToEnd();
var root = JsonConvert.DeserializeObject<List<RootObject>>(json);
var articles = root.Select(m => new Article { Name = m.title, ImagePath = m.images.poster, id = m._id, Year = m.year });
You can use the website http://json2csharp.com/ to generate the C# classes based on the JSON string.
The result sent by http://eztvapi.re/shows/1&query_term=abc is an array of RootObject.
So, in your code, you need to update the line JsonConvert.DeserializeObject to an array of RootObject.
var root = JsonConvert.DeserializeObject<RootObject[]>(json);