<ns2:dni>
<ns2:tipoDocumento>
<ns2:pais>
<ns2:codigo>COL</ns2:codigo>
<ns2:nombre>Colombia</ns2:nombre>
</ns2:pais>
<ns2:codigo>CC</ns2:codigo>
</ns2:tipoDocumento>
<ns2:numero>1144040396</ns2:numero>
<ns2:principal>true</ns2:principal>
<ns2:campoExtension>
<ns2:clave>CIUDAD_DCTO</ns2:clave>
<ns2:valor>76001</ns2:valor>
</ns2:campoExtension>
<ns2:campoExtension>
<ns2:clave>DEPARTAMENTO_DCTO</ns2:clave>
<ns2:valor>76</ns2:valor>
</ns2:campoExtension>
<ns2:campoExtension>
<ns2:clave>PAIS_DCTO</ns2:clave>
<ns2:valor>COL</ns2:valor>
</ns2:campoExtension>
<ns2:campoExtension>
<ns2:clave>LUGAR_EXPEDICION</ns2:clave>
<ns2:valor>CALI</ns2:valor>
</ns2:campoExtension>
</ns2:dni>
So im having problems deserializing this xml document so far i've managed to deserialize "tipoDocumento", "numero", and "principal" correctly, problem is when it reaches the "campoExtension" objects, as you can probably see they're not encapsulated in an object just for them and if i try to create a list in the model it stays empty after deserialization, this is what i get:
"dni": {
"tipoDocumento": {
"pais": {
"codigo": "COL",
"nombre": "Colombia"
},
"codigo": "CC"
},
"numero": "1144040396",
"principal": true,
"campoExtension": []
}
and yes it's a json because im turning it into a c# object so i can serialize with newstonsoft after. please help.
this is my Dni Class:
public class Dni
{
public TipoDocumento tipoDocumento;
public string numero;
public bool principal;
public CampoExtension[] campoExtension;
}
So i found the solution what i did was update my dni class to the following:
[XmlRoot("dni")]
public class Dni
{
public TipoDocumento tipoDocumento;
public string numero;
public bool principal;
[XmlElement("campoExtension")]
public List<CampoExtension> campoExtension;
}
now my json looks like this:
"dni": {
"tipoDocumento": {
"pais": {
"codigo": "COL",
"nombre": "Colombia"
},
"codigo": "CC"
},
"numero": "1144040396",
"principal": true,
"campoExtension": [
{
"clave": "CIUDAD_DCTO",
"valor": "76001"
},
{
"clave": "DEPARTAMENTO_DCTO",
"valor": "76"
},
{
"clave": "PAIS_DCTO",
"valor": "COL"
},
{
"clave": "LUGAR_EXPEDICION",
"valor": "CALI"
}
]
},
Related
In an application written in c# I need to create a JSON string with a certain syntax.
The data to be serialised is a list of different objects.
The syntax looks like this (section of the whole string):
"ShipmentUnit": [{
...
"Services": [{
"Service1": {
"ServiceName": "service_1",
"Property1": "Value1",
"Property2": "Value2"
},
"Service2": {
"ServiceName": "service_2",
"Property3": "Value3",
}
}
]
}
]
I want to provide the data to be serialised in a suitable object structure and then serialise it with Newtonsoft.Json. Unfortunately, this does not work.
If I use an array for the list, the result looks like this:
"ShipmentUnit": [{
...
"Services": [
{
"ServiceName": "service_1",
"Property1": "Value1",
"Property2": "Value2"
},
{
"ServiceName": "service_2",
"Property3": "Value3",
}
}
]
}
]
If I use a dictionary, the result looks like this (the square brackets are missing):
"ShipmentUnit": [{
...
"Services": {
"Service1": {
"ServiceName": "service_1",
"Property1": "Value1",
"Property2": "Value2"
},
"Service2": {
"ServiceName": "service_2",
"Property3": "Value3",
}
}
}
]
I've already read the following topics, but they do not match my problem:
Serialise list of C# custom objects
Serialise list of objects to single JSON object, with property as key
Serialise List<Dictionary<String,Object>>
Any ideas what to do?
try this
Data data=JsonConvert.DeserializeObject<Data>(json);
json=JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);
classes
public class Data
{
public List<ShipmentUnit> ShipmentUnit { get; set; }
}
public class ShipmentUnit
{
public List<Dictionary<string,Dictionary<string,string>>> Services { get; set; }
}
result
{
"ShipmentUnit": [
{
"Services": [
{
"Service1": {
"ServiceName": "service_1",
"Property1": "Value1",
"Property2": "Value2"
},
"Service2": {
"ServiceName": "service_2",
"Property3": "Value3"
}
}
]
}
]
}
I am wondering if we can take some parts inside a JSON string and print it out. I have a JSON string and I only want to take some specific things in it.
My JSON string:
{
"A": {
"a1":[
{
"a11": {
"a111": "something1",
"a112": "something2"
},
"a12": [
{
"a121": "something1",
"a122": "something2"
},
{
"a211": "something1",
"a212": "soemthing2"
}
]
]
},
"B": {
"b1":[
{
"b11": {
"b111": "something1",
"b112": "something2"
},
"b12": [
{
"b121": "something1",
"b122": "something2"
},
{
"b211": "something1",
"b212": "soemthing2"
}
]
}
]
}
}
I only want to print out: b121 is something1. How can I do it in C#?
Firstly, your JSON example has some problems so I'll give an example using this part as the JSON file.
{
"B": {
"b1":
{
"b11": {
"b111": "something1",
"b112": "something2"
},
"b12": [
{
"b121": "something1",
"b122": "something2"
},
{
"b211": "something1",
"b212": "soemthing2"
}
]
}
}
}
You can access to a specific part like this using Json.NET:
var jsonData = File.ReadAllText(#"\test.json");
dynamic jsonObject = JsonConvert.DeserializeObject(jsonData);
// print out a specific part
Console.WriteLine(jsonObject.B.b1.b11.b111);
This question already has answers here:
How to auto-generate a C# class file from a JSON string [closed]
(3 answers)
Closed 4 years ago.
I have the following JSON (not the true data) in the following format, which I am trying to convert into C# equivalent classes. If you noticed that type_1, type_2 these could be in any numbers. which is difficult to put in collection(sort of anonymous). If i remove all type_1, type_2 ... from the JSON it is easy can be converted to classes. Since it in dynamic in nature it is making it difficult.
I have tried http://json2csharp.com/ to get the classes. Problem is, it converts "types" as members, which is not true, it should be a dynamic collection or an array.
This slight different problem
This question has 2 extra problems first "type_1" elements are dynamic and second is these are not in list or an array.
I don't have control over this JSON format which is extra frustration.
{
"type_1": {
"#type": "blob",
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI="
},
"type_2": {
"#type": "blob",
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI="
},
"type_3": {
"#type": "blob",
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI=",
},
"type_4": {
"#type": "blob",
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI=",
},
"type_5": {
"#type": "blob",
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI=",
},
"References": {
"blob_1": {
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI=",
"revpos": 1,
"stub": true
},
"blob_2": {
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI=",
"revpos": 1,
"stub": true
}
},
"someproperty1": "somevalue1",
"someproperty2": "somevalue2",
"someproperty3": "somevalue3",
"someproperty4": "somevalue4",
"someproperty5": "somevalue5"
}
I was thinking something like
Filecollection is nothing but that anonymous collection; no luck ;(
public partial class Doc
{
[JsonProperty("references")]
public Dictionary<String, Attachments> Attachments { get; set; }
public List<Dictionary<String, Details>> FileCollections { get; set; }
[JsonProperty("someproperty")]
public String someproperty { get; set; }
[JsonProperty("someproperty2")]
public String someproperty2 { get; set; }
[JsonProperty("someproperty3")]
public String someproperty3 { get; set; }
}
Based on your comments (hopefully, I understand it)...
{
"unknown_a" : {...},
"unknown_b" : {...},
"unknown_c" : {...},
"unknown_d" : {...},
"foo" : true, // known property
"bar" : { // known property
"x" : "xxx",
"y" : "yyy"
}
}
I'm thinking that you want a Dictionary<string, object>?
Then you can do a little bit of your own conversion magic --- for example (just to get the concept out there)
foreach (d in dictionary)
{
switch (d.Key)
{
case "foo": ... // known property
obj.Foo = (bool)d.Value;
break;
case "bar": ... // known property
obj.Bar = (Bar)d.Value;
break;
default: ... // according to your comments, these are known types
try
{
obj.Files.Add((File)d.Value);
}
catch {...}
break;
}
}
I work with JSON.Net.
I wrote a strongly typed representation for the expected Json :
public BaseClass{
[JsonProperty("fields")]
public Fields Fields { get; set; }
}
public class Fields
{
[JsonProperty("worklog")]
public List<WorkLog> WorkLog { get; set; }
}
Sample of expected Json :
{
"baseprop": {
"fields": {
"worklog": {
"startAt": 0,
"maxResults": 20,
"total": 2,
"worklogs": [
{
"self": "",
"author": {},
"updateAuthor": {},
"comment": "UpdatedcouriersT&C",
"created": "2015-09-04T19: 11: 27.169+0300",
"updated": "2015-09-04T19: 13: 00.567+0300",
"started": "2015-09-04T19: 11: 00.000+0300",
"timeSpent": "1h",
"timeSpentSeconds": 3600,
"id": ""
},
{
"self": "",
"author": {},
"updateAuthor": {},
"comment": "",
"created": "2015-09-07T10: 26: 23.549+0300",
"updated": "2015-09-07T10: 26: 23.549+0300",
"started": "2015-09-07T10: 26: 00.000+0300",
"timeSpent": "10m",
"timeSpentSeconds": 600,
"id": ""
}
]
}
}
}
}
How can I get the value of the property "worklogs" from the "baseprop" element?
I tried something like "[JsonProperty("worklog/worklogs")]" but this doesn't work.
Does JsonProperty support such a thing?
Thanks
I think the confusion comes from the fact that you are trying to remap the complete structure of your JSON to your class.
Perhaps what you should consider is not to deserialize the object, but instead use Linq to Json and assign manually the properties of your BaseClass object as follows :
var jObject = JObject.Parse(jsonString);
BaseClass bc = new BaseClass()
bc.Assignee = jObject["fields"]["worklog"]["worklogs"].First()["assignee"].Value<string>()
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
How do i parse json?
Please tell me the way to deserialize the json data in asp.net c#.
Actually I have a json data with two objects like:
{
"errstr": "All downloded vedios ",
"errcode": 0,
"result": {
"videos": [
{
"id": "22",
"name": "Ashley",
"price": "0.49",
"size": "3712310"
}
],
"trailer": [
{
"id": "1",
"trailer_name": "charl1",
"status": "1"
},
{
"id": "2",
"trailer_name": "charl2",
"status": "1"
}
]
}
}
Here I have two objects videos and trailer. Please tell me the process to get get these data in my code.
you need to create a class with nested members
for example json file
{
"GeminiURL":"https://gemini.com/Gemini"
,"Language":"en"
,"Log":{"Debug":true,"Info":true,"Warn":true,"FileName":"d:\\temp\\tfsgemini.log"}
}
is serializaed and deserialized with c# class
public class Settings
{
public string GeminiURL;
private LogSettings _log;
public LogSettings Log
{
get { return _log = _log ?? new LogSettings(); }
set { _log = value; }
}
public string Language;
public Settings()
{
// defaule settings can be assigned here;
}
}
public class LogSettings
{
public bool Debug;
public bool Info = true;
public bool Warn = true;
public string FileName;
}
and the deserialization code looks like:
public static T Load(string fileName)
{
T t = new T();
if (File.Exists(fileName))
t = (new JavaScriptSerializer()).Deserialize<T>(File.ReadAllText(fileName));
else
Save(t);
return t;
}
JSON .NET - http://json.codeplex.com/