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
Related
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);
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 is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
XML to C# object returning error:
Error is : Data at the root level is invalid. Line 1, position 1.
How to deserialize xml string to c# object?
Here is my XML:
<MSGIDRETURN>
<VERSION>1.0</VERSION>
<MSGID_LIST>
<MSGID>Test1234567</MSGID>
</MSGID_LIST>
</MSGIDRETURN>
Here is my C# Classes:
[XmlRoot("MSGIDRETURN")]
public class MSGIDRETURN
{
[XmlElement("VERSION")]
public string Version { get; set; }
[XmlElement("MSGID_LIST")]
public MSGID_LIST MsgIdList { get; set; }
}
[Serializable()]
public class MSGID_LIST
{
[XmlElement("MSGID")]
public List<string> MsgId { get; set; }
}
And Deserialization Code :
XmlSerializer serializer = new XmlSerializer(typeof(MSGIDRETURN));
StringReader rdr = new StringReader(inputString.Trim());
MSGIDRETURN resultingMessage = (MSGIDRETURN)serializer.Deserialize(rdr);
Just tried your solution, with string instead of input and it's working.
What is your inputString? Is that file or something else?
string testData = #"<MSGIDRETURN>
<VERSION>1.0</VERSION>
<MSGID_LIST>
<MSGID>Test1234567</MSGID>
</MSGID_LIST>
</MSGIDRETURN>";
XmlSerializer serializer = new XmlSerializer(typeof(MSGIDRETURN));
StringReader rdr = new StringReader(testData.Trim());
MSGIDRETURN resultingMessage = (MSGIDRETURN)serializer.Deserialize(rdr);
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());