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" });
}
}
Related
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 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 6 years ago.
Improve this question
I need to access referenced classes inside a main class and insert values into the objects. The classes are of partial type.
my code:
public partial class Get_CountryInfo_Resp_object
{
public string ReturnCode { get; set; }
public string ErrorMsg { get; set; }
public string Alpha2_Code { get; set; }
public string Digit3_Code { get; set; }
public string CountryName { get; set; }
public string IBAN_Mandatory { get; set; }
public As_SenderCountry[] As_SenderCountry { get; set; }
public As_ReceiverCountry[] As_ReceiverCountry { get; set; }
}
public partial class As_SenderCountry
{
public string SenderCountry_IsSensitive { get; set; }
}
public partial class As_ReceiverCountry
{
public string ReceiverCtry_EFTNotAllowed { get; set; }
public ReceiverCtry_AllowedCCY_Item[] ReceiverCtry_AllowedCCY_List { get; set; }
}
public partial class ReceiverCtry_AllowedCCY_Item
{
public string ReceiverCtry_AllowedCCY { get; set; }
}
private static void Task2()
{
String xmlText = File.ReadAllText(#"../../XML/sample1.xml");
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(xmlText)));
DataTable dt = ds.Tables["column"];
Get_CountryInfo_Resp_object Get_CountryInfo_Resp = new Get_CountryInfo_Resp_object();
//Get_CountryInfo_Resp.As_SenderCountry;
Get_CountryInfo_Resp.ReturnCode = dt.Rows[0]["column_Text"].ToString();
Get_CountryInfo_Resp.ErrorMsg = dt.Rows[1]["column_Text"].ToString();
Get_CountryInfo_Resp.Alpha2_Code = dt.Rows[2]["column_Text"].ToString();
Get_CountryInfo_Resp.Digit3_Code = dt.Rows[3]["column_Text"].ToString();
Get_CountryInfo_Resp.CountryName = dt.Rows[4]["column_Text"].ToString();
Get_CountryInfo_Resp.IBAN_Mandatory = dt.Rows[5]["column_Text"].ToString();
//GetCountryInfo_Resp.As_SenderCountry.SenderCountry_IsSensitive
I need to Insert dt.Rows[6]["column_Text"].ToString(); into the GetCountryInfo_Resp.As_SenderCountry.SenderCountry_IsSensitive .
How shall i proceed?
Please help.
Since As_SenderCountry is an array, it can contain multiple items. You have to assign an array too, not just a single instance.
I would start to create an object, add that to a list and eventually create an array out of it (or change the type to be a list instead of an array). You can also fix-size the array if you know the length already.
As_SenderCountry asc = new As_SenderCountry();
asc.SenderCountry_IsSensitive = dt.Rows[6]["column_Text"].ToString();
And then:
GetCountryInfo_Resp.As_SenderCountry = new As_SenderCountry[] { asc };
Or create the list, loop over items and eventually assign it:
List<As_SenderCountry> list = new List<As_SenderCountry>();
// some sort of loop
As_SenderCountry asc = new As_SenderCountry();
...
list.Add(asc);
// end loop
GetCountryInfo_Resp.As_SenderCountry = list.ToArray();
I don't think I fully understand your code, but As_SenderCountry and As_ReceiverCountry in your public partial class Get_CountryInfo_Resp_object are arrays, if I am not reading it wrong.
Therefore, the messy solution, if you know there is only one sender country:
GetCountryInfo_Resp.As_SenderCountry[0].SenderCountry_IsSensitive = dt.Rows[6]["column_Text"].ToString();
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating. An example with your variables:
public partial class Get_CountryInfo_Resp_object
{
public string ReturnCode { get; set; }
...
public List<As_SenderCountry> As_SenderCountry { get; set; }
public List<As_ReceiverCountry> As_ReceiverCountry { get; set; }
}
private static void Task2()
{
String xmlText = File.ReadAllText(#"../../XML/sample1.xml");
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(xmlText)));
DataTable dt = ds.Tables["column"];
Get_CountryInfo_Resp_object Get_CountryInfo_Resp = new Get_CountryInfo_Resp_object();
...
GetCountryInfo_Resp.As_SenderCountry.SenderCountry_IsSensitive.Add(dt.Rows[6]["column_Text"].ToString());
p.s. Your variable and class naming is very messy. I would suggest you to clean that up so that you, as well as the people reading the question can understand it better.
You need to create a new instance of the inner class as you would do normally for any other class, and then assign whatever value to the field you need.
First you need to assign the length of the array, then each cell of the array will contain an instance of an object of type (As_SenderCountry ), then you should assign each object the value you need.
GetCountryInfo_Resp.As_SenderCountry = new GetCountryInfo_Resp.As_SenderCountry();
GetCountryInfo_Resp.As_SenderCountry[INDEX_HERE].SenderCountry_IsSensitive = dt.Rows[6]["column_Text"].ToString();
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);
I'm having an instance where I have an object that looks similar to this:
public class answerObject
{
public string Q1 { get; set; }
public string Q2 { get; set; }
public string Q3 { get; set; }
public string Q4 { get; set; }
public string Q5 { get; set; }
...
public string Q80 { get; set; }
}
The questions themselves look like this:
public class questionObject
{
public string DataMember { get; set; }
...
}
The DataMember string carries a string version of the answer object element. So, if I have question 1 have a datamember of "Q1" then I want it to fill in answerObject.Q1 and so on. Right now I have a lengthy switch statement to solve this, but there has to be a more efficient way to do this.
switch(DataMember) {
case "Q1":
answerObject.Q1 = answerValue;
break;
case "Q2":
answerObject.Q2 = answerValue;
break;
....
};
I've researched for a few hours and didn't come up with anything. Any help is much appreciated.
You can use Reflection for that but I would keep using the switch/case:
var property = typeof(answerObject).GetProperty(DataMember);
if(property != null) property.SetValue(yourInstance, answerValue);
After your edit using Reflection makes more sense.Anyway you can also put this code into an extension method:
public static void SetAnswer(this answerObject instance, string question, string value)
{
var property = typeof(answerObject).GetProperty(question);
if (property != null) property.SetValue(instance, value);
else { // throw exception or display a message }
}
A possible solution is to use a Dictionary object - make your Questions a dictionary and set the string Q1, Q2, etc. as key (your DataMember would later be filled with one of the keys). Then to assign the question just use the already set DataMember and the item property of the Dictionary object. The code could look like this:
public class QuestionObject
{
public string DataMember { get; set; }
public String Answer { get; set; }
}
public class AnswerObject
{
public Dictionary<String, String> Questions { get; set; }
public AnswerObject()
{
Questions = new Dictionary<String, String>();
// init the question keys
Enumerable.Range(1, 80).ToList().ForEach(index =>
{
Questions.Add(String.Format("Q{0}", index), String.Empty);
});
}
}
And the usage looks like this:
var question = new QuestionObject();
var answer = new AnswerObject();
question.DataMember = #"Q75";
// set the question = the same as the switch/case
answer.Questions[question.DataMember] = #"and the answer is ...";