C# Read Json And Read Data [closed] - c#

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; }
}
}

Related

Make JSON object with variables C# [closed]

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);
}

How to parse JSON list or object in C# [closed]

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.

Create JSON array in C# with asp.net [closed]

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

How can I get a list from a json file in c#? [closed]

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);

Convert string from webservice to LIST [closed]

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 8 years ago.
Improve this question
I receive from client a raw string as this:
{ "\"wrapper\": {\"system\": { \"session\":\"ed6d1cc6-82f9-46e8-91bb-eae341a771cf\", \"ip\":\"\", \"station\":\"\"},{ \"personal_profile\": {\"suffix\":\"1096\",\"first_name\":\"Varvara\",\"middle_name\":\"\",\"last_name\":\"Terlouw\",\"street\":\"\",\"number\":\"\",\"add\":\"\",\"postal\":\"\",\"city\":\"\",\"state\":\"\",\"country\":\"\",\"birthday\":\"\",\"relation_type_id\":\"\"}},{ \"personal_contacts\": {\"contact_type_id_0\":\"409\",\"contact_0\":\"06-26096994\",\"contact_0\":\"on\"},{\"contact_type_id_0\":\"420\",\"contact_0\":\"jj#vv.com\",\"contact_0\":\"on\"},{\"contact_type_id_0\":\"\",\"contact_0\":\"\",\"contact_0\":\"on\"}},{ \"personal_work\": {}},{\"personal_connected\": {}},{\"personal_interests\": {}}}} "
I get the string in into my webservice and need to convert this to LIST<> so I can process the data to my database, preferable with my classes
here and old example of a class i used a while ago as another example for simple json serialize :
internal class CFingerPrint
{
public string WanIP;
public string MacAddress;
public string getClassEncrypted()
{
return new JavaScriptSerializer().Serialize(this);
}
public CFingerPrint getClassDecrypted(string sSerializedClass)
{
return new JavaScriptSerializer().Deserialize<CFingerPrint>(sSerializedClass);
}
}
I use the same way to communicate with other languages a lot and haven't had any issue yet except Dates that are problematic in JSON but that's another story.
Edit : example how to use :
// create new class
var originalClass = new CFingerPrint();
// fill some data
originalClass.WanIP = "test1";
originalClass.MacAddress= "test2";
// serialize to json string
var classSerialized = originalClass.getClassEncrypted();
// create new class from string only
var newClass = new CFingerPrint().getClassDecrypted(classSerialized);
Console.WriteLine(newClass.WanIP); // output "test1"
Console.WriteLine(newClass.MacAddress); // output "test2"
Example with childs :
public class Manufacturer
{
public string Name{ get; set; }
public List<Motor> AvailaibleMotors{ get; set; }
public string getClassSerialized()
{
return new JavaScriptSerializer().Serialize(this);
}
public ManufacturergetClassDeSerialized(string sSerializedClass)
{
return new JavaScriptSerializer().Deserialize<Manufacturer>(sSerializedClass);
}
}
public class Motor
{
public string Model { get; set; }
public List<Voltage> Voltages { get; set; }
}
public class Voltage
{
public int Volt { get; set; }
public int Phase { get; set; }
public int Frequency { get; set; }
}
so manufacturer can have one or many motors which can have one of many voltage and this works perfectly no matter what.
You can probably do something like this too.
public ActionResult jsonPull()
{
try
{
using (var webClient = new System.Net.WebClient())
{
webClient.Encoding = Encoding.UTF8;
var json = webClient.DownloadString("example.com/json");
var parsed = JsonConvert.DeserializeObject(json);
return Json(parsed);
}
}
catch (Exception e)
{
return Json(new { json = "error" });
}
}

Categories