This question already has answers here:
Deserialize JSON with C#
(10 answers)
How can I deserialize JSON with C#?
(19 answers)
Closed 8 months ago.
I am looking for a way to convert the following manually typed JSON list to a List I can load, but still output the same format in C#, so in can be POSTed to a REST API.
var accs = #"{
" + "\n" +
#" ""Cities"": [
" + "\n" +
#" ""Atlanta"",
" + "\n" +
#" ""Chicago"",
" + "\n" +
#" ""San Diego""
" + "\n" +
#" ]
" + "\n" +
#"}
" + "\n" +
#"";
Assuming this is your model:
public class State
{
public List<string> Cities { get; set; }
public State(List<string> cities)
{
Cities = cities;
}
}
This is how you serialize and deserialize:
using System.Text.Json;
var listOfCities = new List<string>() { "Atlanta", "Chicago", "San Diego"};
var state = new State(listOfCities);
//Serialize
var jsonArray = JsonSerializer.Serialize(state);
// Deserialize
var obj = JsonSerializer.Deserialize<State>(jsonArray);
When you use #", you can avoid the + concatenation like:
var accs = #"
{
'Cities': [
'Atlanta',
'Chicago',
'San Diego'
]
}
";
You'll need to use ' (single quotes) instead of " in your JSON text, otherwise you have to escape \" them.
you don't need any custom classes, you can just parse your json string
using Newtonsoft.Json;
var jsonParsed=JObject.Parse(accs);
if you need list of cities as c# instance
List<string> cities =jsonParsed["Cities"].ToObject<List<string>>();
if you need just a well formatted json string
accs = jsonParsed.ToString();
result
{
"Cities": [
"Atlanta",
"Chicago",
"San Diego"
]
}
Related
This question already has answers here:
Send JSON via POST in C# and Receive the JSON returned?
(4 answers)
Closed 1 year ago.
{
"name": "group1",
"userData": "user-provided data attached to the person group.",
"recognitionModel": "recognition_03"
}
If I need to pass the above body in a http client call how do I format that in C#?
Maybe you find your anwser here:
public void JsonStringExample()
{
string example1 = #"{
""name"": ""group1"",
""userData"": ""user-provided data attached to the person group."",
""recognitionModel"": ""recognition_03""
}";
string example2 = "{"
+ " \"name\": \"group1\","
+ " \"userData\": \"user-provided data attached to the person group.\","
+ " \"recognitionModel\": \"recognition_03\""
+ "}";
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("{");
stringBuilder.AppendLine(" \"name\": \"group1\",");
stringBuilder.AppendLine(" \"userData\": \"user-provided data attached to the person group.\",");
stringBuilder.AppendLine(" \"recognitionModel\": \"recognition_03\"");
stringBuilder.AppendLine("}");
string example3 = stringBuilder.ToString();
string exmaple4 = String.Join(
"\r\n",
new string[]
{
"{",
" \"name\": \"group1\",",
" \"userData\": \"user-provided data attached to the person group.\",",
" \"recognitionModel\": \"recognition_03\"",
"}"
}
);
}
This question already has answers here:
How to get attribute in the XDocument object
(2 answers)
Closed 4 years ago.
Here is my code so far:
XDocument document = XDocument.Load("C:\\modinfo.xml");
var elements = from r in document.Descendants("Mod")
select new
{
Author = r.Element("Author").Value,
Description = r.Element("Description").Value
};
foreach (var r in elements)
{
Console.WriteLine("AUTHOR = " + r.Author + Environment.NewLine + "DESCRIPTION = " + r.Description);
}
And this is my "modinfo.xml" file:
<Mod Name="Mod Name">
<Author>Author Name</Author>
<Description>Description Text</Description>
</Mod>
At the moment, it looks like
when I run the application. What I am trying to do is for it to also print "Mod Name" in it also.
Just select the Mod Name in your anonymous type:
var elements = from r in document.Descendants("Mod")
select new
{
ModName = r.Attribute("Name").Value,
Author = r.Element("Author").Value,
Description = r.Element("Description").Value
};
foreach (var r in elements)
{
Console.WriteLine("MOD Name = " + r.ModName + Environment.NewLine + "AUTHOR = " + r.Author + Environment.NewLine + "DESCRIPTION = " + r.Description);
}
If this is your complete xml, following should help you as you do not have multiple Mods.
XElement xmlTree = XElement.Parse(str);
var result = new {
Author = xmlTree.Element("Author").Value,
Description = xmlTree.Element("Description").Value,
Name =xmlTree.Attribute("Name").Value
};
Input
<Mod Name="Mod Name">
<Author>Author Name</Author>
<Description>Description Text</Description>
</Mod>
Output
Author : Author Name
Description : Description Text
Name :Mod Name
I've been successfully using JToken and JArray to grab specific pieces of data, but I'm having one particular issue. The issues lie with extracting the values from the key/value pairs in my node 'work_unit.' You can see the node here in my JObject:
JObject testString = JObject.Parse("{"
+ "'Roofing': {"
+ "'Buildings': ["
+ "{"
+ "'BuildingId': 4,"
+ "'BuildingName': 'what',"
+ "'work_unit': '{\"RoofingBuildings\":\"1\",\"WindowsBuildings\":\"\",\"GutterBuildings\":\"\",\"InsulationMasterPrice\":\"\",\"SidingBuildings\":\"\"}'"
+ "},"
+ "{"
+ "'BuildingId': 3,"
+ "'BuildingName': 'Home'"
+ "}"
+ "],"
+ "'Windows': ["
+ "{"
+ "'PerimeterDrawings': 56,"
+ "},"
+ "{"
+ "'PerimeterDrawings': 55,"
+ "}"
+ "]"
+ "},"
+ "'Window':"
+ "{"
+ "'poof': 3,"
+ "'stall': 7"
+ "},"
+ "'Products': ["
+ "'Roofing',"
+ "'Pooping',"
+ "],"
+ "'Garage': ["
+ "{"
+ "'roof': 3,"
+ "'wall': 7"
+ "},"
+ "{"
+ "'roof': 3,"
+ "'wall': 7"
+ "}"
+ "]"
+ "}");
I can get the entirety of 'work_unit' like so:
JToken jt= JO.SelectToken("Roofing.Buildings[0].work_unit");
^^ jt will contain:
{{"RoofingBuildings":"1","WindowsBuildings":"","GutterBuildings":"","InsulationMasterPrice":"","SidingBuildings":""}}
How do I get the "1" from RoofingBuildings? I've tried several methods, here are some, but they just end up being null.
string foo1 = (string)JTNewTest.SelectToken(".RoofingBuildings");
string foo2 = (string)JO.SelectToken("Roofing.Buildings[0].work_unit[0].RoofingBuildings");
Thanks in advance, I couldn't find my exact situation in any other online examples for some reason :/
You can get it like this, I assumed that the work_unit was supposed to be split up into it's own properties rather than being a string.. Hopefully I was correct in that assumption. Also made multi-line string for readability sake.
JObject testString = JObject.Parse(#"
{
'Roofing': {
'Buildings':
[
{
'BuildingId': 4,
'BuildingName': 'what',
'work_unit':
{
'RoofingBuildings':'1',
'WindowsBuildings':'',
'GutterBuildings':'',
'InsulationMasterPrice':'',
'SidingBuildings':''
}
},
{
'BuildingId': 3,
'BuildingName': 'Home'
}
],
'Windows':
[
{
'PerimeterDrawings': 56,
},
{
'PerimeterDrawings': 55,
}
]
},
'Window':
{
'poof': 3,
'stall': 7
},
'Products':
[
'Roofing',
'Pooping'
],
'Garage':
[
{
'roof': 3,
'wall': 7
},
{
'roof': 3,
'wall': 7
}
]
}");
var roofingBuildings = testString["Roofing"]["Buildings"][0]["work_unit"]["RoofingBuildings"];
Console.WriteLine("RoofingBuildings: {0}", roofingBuildings);
I know I've not gone about this in the easiest of manners but i'm fairly new to C#.
I'm trying to make sure that when I select from only 1,2,3 or 4 of the 5 checked list boxes that i do not end up with the following
&& or &&& etc... I would like the final string to be xxxxx&xxxxx&xxx or similar as the String is added to a preset SQL query.
Code is below:
any help would be appreciated I've had a look around online for some help but not found much I was able to get my head round.
List<object> list = checkedListBox1.CheckedItems.OfType<object>().ToList();
List<object> list2 = checkedListBox2.CheckedItems.OfType<object>().ToList();
List<object> list3 = checkedListBox3.CheckedItems.OfType<object>().ToList();
List<object> list4 = checkedListBox4.CheckedItems.OfType<object>().ToList();
List<object> list5 = checkedListBox5.CheckedItems.OfType<object>().ToList();
string selected_fields_cb1 = string.Join(" ", list.ToArray());
string selected_fields_cb2 = string.Join(" ", list2.ToArray());
string selected_fields_cb3 = string.Join(" ", list3.ToArray());
string selected_fields_cb4 = string.Join(" ", list4.ToArray());
string selected_fields_cb5 = string.Join(" ", list5.ToArray());
string allSelected = (selected_fields_cb1 + " " + selected_fields_cb2 + " " + selected_fields_cb3 +
" " + selected_fields_cb4 + " " + selected_fields_cb5 + "");
string allSelected2 = allSelected.Replace( " ", "&" );
string allSelected3 = allSelected2.TrimEnd('&');
If I understand well, you try to add spaces and then replace these spaces by &.
It would be easier to do this directly.
List<object> list = checkedListBox1.CheckedItems.OfType<object>().ToList();
List<object> list2 = checkedListBox2.CheckedItems.OfType<object>().ToList();
List<object> list3 = checkedListBox3.CheckedItems.OfType<object>().ToList();
List<object> list4 = checkedListBox4.CheckedItems.OfType<object>().ToList();
List<object> list5 = checkedListBox5.CheckedItems.OfType<object>().ToList();
var allObjects = list.Concat(list2).Concat(list3).Concat(list4).Concat(list5);
var res = string.Join("&", allObjects);
This question already has answers here:
Escape double quotes in a string
(9 answers)
How can I add double quotes to a string that is inside a variable?
(20 answers)
Closed 7 years ago.
I have been looking at this for a while trying everything I can find on SO. There are many posts but I must be missing something.
I am building a string and need to get a double quote in it between two variables.
I want the string to be
convert -density 150 "L:\03 Supervisors\
The code is
tw.WriteLine(strPrefix + " " + strLastPath);
where
strPrefix = convert -density 150
and
strLastPath = L:\\03 Supervisors\
I have tried many combinations of "" """ """" \" "\ in the middle where the space is being inserted.
Please show me what I am missing.
You have two options:
var output1 = strPrefix + "\"" + strLastPath;
Or using a verbatim string:
var output2 = strPrefix + #"""" + strLastPath;
Here's a sample console application that achieves what you're after:
namespace DoubleQuote
{
class Program
{
static void Main(string[] args)
{
var strPrefix = "convert - density 150";
var strLastPath = #"L:\\03 Supervisors\";
Console.WriteLine(strPrefix + " \"" + strLastPath);
Console.ReadKey();
}
}
}
If written as a format string it would look like this:
var textToOutput = string.Format("{0} \"{1}", strPrefix, strLastPath);
Console.WriteLine(textToOutput);
Please try this
var strPrefix = "convert -density 150";
var strLastPath = #"L:\03 Supervisors\";
Console.WriteLine(strPrefix + " " + '"'+strLastPath);