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

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

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 in C# object the {"Europe":{"France":"Paris","UK":"London","Germany":"Berlin"}} Json object where the keys are actual object values? [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 1 year ago.
Improve this question
Update: I think I have to rephrase the question: I'm getting the continent, country and capital lists from lets say a db source and I have to construct a JSON object that has the given structure.
I have to create a Dto object that represents the following JSON object format:
{
"Europe":{
"France":"Paris",
"UK":"London",
"Germany":"Berlin"
}
}
where "Europe" is a value for an object of type Continent and "France", "UK" and "London" are values of the object Country:
public class Country
{
public string Name { get; set; }
public string Capital { get; set; }
}
How would you represent that JSON object with object classes?
Use a proxy Dictionary<string, Dictionary<string, string>> as suggested by #
Camilo-Terevinto
using System.Text.Json.Serialization;
using System.Text.Json;
public class Continent
{
public string Name { get; set; }
public List<Country> Countries { get; set; } = new List<Country>();
}
public class Country
{
public string Name { get; set; }
public string Capital { get; set; }
}
string json = #"
{
""Europe"":{
""France"":""Paris"",
""UK"":""London"",
""Germany"":""Berlin""
}
}
";
var dic = JsonSerializer.Deserialize<Dictionary<string,Dictionary<string,string>>>(json);
var continents = new List<Continent>();
foreach(var key in dic.Keys) {
var continent = new Continent() { Name = key };
foreach(var subkey in dic[key].Keys)
{
continent.Countries.Add(new Country() { Name = subkey, Capital = dic[key][subkey] });
}
continents.Add(continent);
}
try this
var json="{\"Europe\":{\"France\":\"Paris\",\"UK\":\"London\",\"Germany\":\"Berlin\"}}";
var result= JsonConvert.DeserializeObject<EuropeCountry>));
var continent = new Continent {
Name = nameof( result.Europe),
Countries = result.Europe.Select(e => new Country {Name=e.Key, Capital=e.Value} ).ToList()
};
public class Continent
{
public string Name { get; set; }
public List<Country> Countries { get; set; }
}
public class EuropeCountries
{
public Dictionary<string, string> Europe {get;set;}
}

How to parse complex json to c# .net classes [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 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);

How to define a C# class model for these dataobjects [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 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; }
}

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