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
my json is as given below. i need to convert it into c# class. Please note all values will be different in actual scenario.
{
'aa-AA': {
lanCODE: 'aa-AA',
genNames: {
female: ['Wavenet'],
male: ['Bavenet', 'Bavenet'],
},
default: 'Wavenet',
systemLocale: ['ara', 'aru', 'are', 'aro', 'arh', 'arm', 'arq', 'ark'],
name: 'xxxx',
},
'aa-AA': {
lanCODE: 'aa-AA',
genNames: {
female: ['Wavenet'],
male: ['Bavenet', 'Bavenet'],
},
default: 'Wavenet',
systemLocale: ['ara', 'aru', 'are', 'aro', 'arh', 'arm', 'arq', 'ark'],
name: 'xxxx',
},
'aa-AA': {
lanCODE: 'aa-AA',
genNames: {
female: ['Wavenet'],
male: ['Bavenet', 'Bavenet'],
},
default: 'Wavenet',
systemLocale: ['ara', 'aru', 'are', 'aro', 'arh', 'arm', 'arq', 'ark'],
name: 'xxxx',
}
}
The initial property is almost certainly meant to be a dictionary key, so I would go with something like this:
public class Language
{
[JsonProperty("lanCODE")]
public string LanguageCode { get; set; }
public string Default { get; set; }
public List<string> SystemLocale { get; set; }
public GenNames GenNames { get; set; }
}
public class GenNames
{
public List<string> Female { get; set; }
public List<string> Male { get; set; }
}
And deserialise like this:
var languages = JsonConvert.DeserializeObject<Dictionary<string, Language>>(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
My C# application has the below json which is deserialized to a dictionary which is assigned to values:
{
"armSpan": 1.8081974983215332,
"handPosition": {
"x": 1.23,
"y": 1.74,
"z": 2.05,
}
}
This is the code which deserializes:
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
I want to assign data from it to various fields in my Size model. For armSpan I'm happy that the following works:
size.ArmSpan = decimal.Parse(values["armSpan"]);
I'm not sure how to get the values of x, y and z though. should it be something like
size.HandPosX = decimal.Parse(values["handPosition"]["x"]);
or
size.HandPosX = decimal.Parse(values["handPosition"].["x"]);
There are online converters to generate c# code based on your json (search for "JSON to C#"). With one of those, I made these classes based on the json you supplied (removed the extra comma in '"z": 2.05,'):
public partial class ClassYouDeserializeTo
{
[JsonProperty("armSpan")]
public double ArmSpan { get; set; }
[JsonProperty("handPosition")]
public HandPosition HandPosition { get; set; }
}
public partial class HandPosition
{
[JsonProperty("x")]
public double X { get; set; }
[JsonProperty("y")]
public double Y { get; set; }
[JsonProperty("z")]
public double Z { get; set; }
}
You can use them like this:
var values = JsonConvert.DeserializeObject<ClassYouDeserializeTo>(response);
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 2 years ago.
Improve this question
How can I define classes with properties where the following code would compile and be valid?
AtomEntry newPost = new AtomEntry();
newPost.Title.Text = "Marriage!";
newPost.Content = new AtomContent();
newPost.Content.Content = "<div xmlns='http://www.w3.org/1999/xhtml'>" +
"<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>" +
"<p>He is the last man on earth I would ever desire to marry.</p>" +
"<p>Whatever shall I do?</p>" +
"</div>";
newPost.Content.Type = "xhtml";
This should do it:
public class AtomEntry
{
public AtomContent Content { get; set; }
public Title Title { get; set; }
}
public class AtomContent
{
public string Content { get; set; }
public string Type { get; set; }
}
public class Title
{
public string Text { 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 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 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" });
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
my task is to group the data from a list of Subscription object which has the following structure:
public class Subscription
{
public string ApplicationId { get; private set; }
public string UserCode { get; private set; }
public string SubscriptionId { get; private set; }
public string SubscriptionCode { get; private set; }
public DateTime? StartDate { get; private set; }
public DateTime? EndDate { get; private set; }
}
The code return a list of subscription, so List. In my case I've several items with same ApplicationId but different StartDate and EndDate. Basically I have to group these items
in order to create a json structure like this:
"applicationId" : {
"subscriptions" : [
{
"startdate" : ...,
"enddate" : ...,
},
{
"startdate" : ...,
"enddate" : ...,
},
]
}
Can I achieve this using LINQ?
Try this:
subscriptions.GroupBy(item => item.SubscriptionCode)
.Select(group => new { Subscription = group.Key, Items = group.Select(item => new { StartDate = item.StartDate, EndDate = item.EndDate}) })
Not sure if it will work but it reads like it will.
subscriptions is just a list of your object.