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 3 years ago.
Improve this question
I have a dynamic object that I have to convert to json (anonymous) for passing to an API as param. What is the best way to do this conversion?
There is this post:
How to convert a dynamic object to JSON string c#?
But this does not quite apply to me as I cannot use var as explained in the comment below.
Thanks
Anand
Trying to covert
dynamic d = new ExpandoObject()
d.prop = "value"
To:
var json = new {prop = "value"}
If you are in .NET Core You can use System.Text.Json;and serialize as dynamic
public static void Main()
{
dynamic w = new ExpandoObject() { Date = DateTime.Now, Item1 = 30 };
w.Item2 = 123;
Console.WriteLine(JsonSerializer.Serialize<dynamic>(w));
}
class ExpandoObject
{
public DateTimeOffset Date { get; set; }
public int Item1 { get; set; }
public int Item2 { get; set; }
}
fiddle here
But I do not understand why do you need to use dynamic (probably there is some logic behind it)
if you are in .Net Framework you need to use Newtonsoft Json which is basically the same stuff
dynamic results = JsonConvert.SerializeObject<dynamic>(w);
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 3 years ago.
Improve this question
I don´t know what I´m doing wrong, but this is the Json I´m trying to read:
[{
"object":
{
"Weigh": 4000
}
}]
I really don´t know why I need the "object": part, but if I remove it, the code doesn´t work.
Here is my API Rest:
[HttpPost]
public string GetMixerTime([FromBody]JsonObject<WeighMix>[] json)
{
IList<WeighMix> listawm = JsonConvert.DeserializeObject<List<WeighMix>>(json.ToString());
return listawm.ToString();
}
WeighMix class:
public class WeighMix
{
public double Weigh { get; set; }
public WeighMix()
{
}
public WeighMix(double weigh)
{
Weigh = weigh;
}
}
Thanks a lot.
The Square Brackets signifies Arrays in Json. Your Json is an array of type (say) A, which has a single property called object of type B (B matches the definition of WeighMix).
You need to change your class declaration as
public class RootObject
{
[JsonProperty("object")]
public WeighMix Object{get;set;}
}
// Define other methods and classes here
public class WeighMix
{
public double Weigh { get; set; }
public WeighMix()
{
}
public WeighMix(double weigh)
{
Weigh = weigh;
}
}
You can now deserialize using
var result = JsonConvert.DeserializeObject<List<RootObject>>(json);
Sample Input
var json = #"[ { 'object': { 'weigh': 4000.0 }, 'json': '{\'Weigh\':4000.0}' } ]";
Sample Output
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 5 years ago.
Improve this question
So this is the code:
class Program
{
static void Main(string[] args)
{
Type T = Type.GetType("CSharpLearningPurposes.Program");
PropertyInfo[] properties = T.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(property.PropertyType.Name);
}
}
}
More specifically, the question is about this line of the code:
Console.WriteLine(propert.PropertyType.Name);
You see here that I access property.PropertyType okay I understand that I am accessing the object's member but I don't understand this: property.PropertyType.Name
What's that doing exactly? Can anybody explain me?
Suppose the following classes:
public class A {
public B Prop {get;set;}
}
public class B {
public string Name {get;set;}
}
If you had an instance of A setup like so:
var example = new A { Prop = new B { Name = "The Name" } };
Then example.Prop.Name would return "The Name" by way of having returned the instance of B assigned to Prop.
You could break this down into a longer form to get an example of how the access works and see how chaining the calls is helpful from a productivity standpoint.
B propVal = example.Prop;
string nameVal = propVal.Name;
Console.WriteLine(nameVal == example.Prop.Name); // True
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 have a JSON string which looks like:
[{"Id":"1","Name":"Apple "},{"Id":"2","Name":"Orange "},{"Id":"3","Name":"Banana "}....]
How can I convert the JSON string to this format: {"1":"Apple"},{"2":"Orange"},{"3","Banana"}... so I can create dictionary like:
Dictionary<string, string> d = new Dictionary<string, string>()
{
{"1":"Apple"},{"2":"Orange"},{"3","Banana"}
};
You don't need to actually transform your original string to another format.
With the use of an intermediary class, as shown below, you can convert directly:
using Newtonsoft.Json;
using System.Linq;
Dictionary<string, string> tt = JsonConvert.DeserializeObject<List<DataObject>>(#"[{""Id"":""1"",""Name"":""Apple ""},{""Id"":""2"",""Name"":""Orange ""},{""Id"":""3"",""Name"":""Banana ""}]").ToDictionary(k => k.Id, v => v.Name);
public class DataObject
{
public string Id { get; set; }
public string Name { get; set; }
}
So what this does is first convert the Json array into a List<DataObject>, and then using the Linq ToDictionary operator we complete the job.
Hope this helps
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
Of course it's easy to write the code to deserialize from this format. I've already done it, but I don't like.
The single responsibility principle states that I should have a generic class that worries only about this kind of serialization. And the task is generic enough to be coped by a framework.
If you converted it to a JSON string like (which should be easy)
var jsonArray = “[{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}]”;
then you could easily deserialize it with Json.NET into whatever you want and Json.NET takes care of converting the values to the right types for you:
MyType1[] result = JsonConvert.Deserialize<MyType1[]>(jsonArray);
MyType2[] result = JsonConvert.Deserialize<MyType2[]>(jsonArray);
public class MyType1
{
public string key { get; set; }
public string value { get; set; }
}
public class MyType2
{
public string key { get; set; }
public double value { get; set; }
}
or even just as a dictionary (I hope I have the syntax correct, I didn't test it):
var jsonDic = “{{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}}”;
var result = JsonConvert.Deserialize<Dictionary<string, string>>(jsonDic);
The single responsibility class (just as an example):
public class KeyValueParser
{
public static TResult ParseKeyValueString<TResult>(string keyValueString)
{
keyValueString = ConvertToJson(keyValueString);
TResul result = JsonConvert.DeserializeObject<TResult>(keyValueString);
return result;
}
private static string ConvertToJson(string keyValueString)
{
// convert keyValueString to json
}
}
usage
var jsonDic = “{{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}}”;
var result = KeyValueParser.ParseKeyValueString<Dictionary<string, string>>(jsonDic);
I don't really understand the question.
If it is something your program does a lot then move the function to some area that it is easy to get too (or a nuget package if a lot of your systems need it). If it happens in one place in your code put it quite close to that place.
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 would like to create a new object that is the instance of the following class.
How to make the object created by relfection equals the instance of the object represented by the class below with reflection c #?
public class cPerson
{
public String name { set; get; }
public String adress { set; get; }
public String phone { set; get; }
}
Maybe you're looking for something like Activator:
var person = Activator.CreateInstance(typeof(cPerson));
Of course, you'll probably be using it when the type is unknown at design time, to create object of the same type...
var newInstance = Activator.CreateInstance(p.GetType());