Parse nested values in C# dictionary [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 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);

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 Json Deserialize jsonstring [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
i have a returned string looks like this
"{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}"
i have tries to Deserialize by using dictionary but still not catching the data.
the most important data is just named inside the properties, item1, item2
System.Text.Json.JsonSerializer.Deserialize<IDictionary<string, object>>(jsonString)
and it' giving the folowing result
[0] [KeyValuePair]:{[properties, {"Item1":{"dataType":"string"},"item2":{"dataType":"string"}
Key [string]:"properties"
Value [object]:ValueKind = Object : "{"item1":{"dataType":"string"},"item2":{"dataType":"string"}
Key [string]:"lastModified"
[1] [KeyValuePair]:{[lastModified, 2021-12-09T19:00:12Z]}
You can deserialize the JSON string to an object by following these simple steps:
Create a C# class from the JSON data. To do this, copy the JSON string and go to VS, Edit, Paste Special, Paste JSON as Classes.
if successful, you will get a C# class like this one
public class Rootobject
{
public Properties properties { get; set; }
public DateTime lastModified { get; set; }
}
public class Properties
{
public Item1 item1 { get; set; }
public Item2 item2 { get; set; }
}
public class Item1
{
public string dataType { get; set; }
}
public class Item2
{
public string dataType { get; set; }
}
You can rename the classes to anything that make meaning to you.
The you can deserialize like this
var obj = JsonConvert.DeserializeObject<Rootobject>(
"{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
Console.WriteLine(obj.properties.item2.dataType)// string
If you only need the value of dataType property and not the whole object, than you can use Linq to Json to get it without deserialization and object mapping.
The examples:
var obj = JObject.Parse("{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
var fistItemDataTypeValue = (string)obj["properties"]?["item1"]["dataType"];
var secondItemDataTypeValue = (string)obj["properties"]?["item2"]["dataType"];
Getting values as list of strings (NOTES: if you already know the number of items in json):
var obj = JObject.Parse("{\"properties\":{\"item1\":{\"dataType\":\"string\"},\"item2\":{\"dataType\":\"string\"}},\"lastModified\":\"2021-12-09T18:20:29Z\"}");
var listOfValues = new List<string>();
for (int i = 1; i <= 2; i++)
{
listOfValues.Add((string)obj["properties"]?[$"item{i}"]["dataType"]);
}
! More about linq to json

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

Order list where date is string [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 9 years ago.
Improve this question
I have three classes :
public class QData
{
public List<RData> Items { get; set; }
public List<QDay> Dates { get; set; }
}
public class QDay
{
public string Date { get; set; }
public List<RData> Details { get; set; }
}
public class RData
{
public string Name { get; set; }
public int Quantity { get; set; }
}
my list is
List<QData> myList;
What is the most effective way to sort the list (*QData type) by Date, the Date is string.
Perhaps this is what you need:
var result = myList.Select(qData => new QData()
{
Items = qData.Items,
Dates = qData.Dates.OrderBy(qDay => DateTime.Parse(qDay.Date)).ToList();
}).ToList();
With DateTime.Parse call being perhaps modified to fit to the date format in the qDay.Date property.
Here is an example that sort using the first date in the Dates list. I can't imagine why you would ever want to do this but here it is. I suspect that having Dates be a list is a mistake, in fact you only want one date there.
var sortedList = MyList.OrderBy(element => DateTime.Parse(element.Dates.First().Date));
I think this is what you actually want... ONLY ONE LIST:
public class QData
{
RData itemInfo { get; set;}
QDay dateInfo { get; set; }
}
Then your sort would look like this:
var sortedList = MyList.OrderBy(element => DateTime.Parse(element.dateInfo.Date));
var temp = (from e in myList.Dates
orderby DateTime.Parse(e.Date)
select e
).ToList();
myList.Dates = temp;

Categories