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;
}
}
Related
This NEST wildcard search is returning zero (0) documents, even though it should because there is data in my index that has this criteria. It is a valid connection and there are no errors showing when setting breakpoints. Any Ideas?
public class Book_ES
{
public string book_title { get; set; }
public string book_author { get; set; }
}
sr_detailed = new SearchDescriptor<Book_ES>()
.Index("books_3").Take(10000)
.Query(a => a
.Bool(b => b
.Should(c => c
.Wildcard(d => d
.Field(f=>f.book_title).Field(g=>g.book_author).Value("A*")
)
)
)
).Highlight(h => h.Fields(f => f.Field("*").PreTags("<span class='hit' style='background-color:yellow'>").PostTags("</span>")))
;
var results = Esclient.Search<Book_ES>(sr_detailed);
You didn't share your mapping but I assume it looks like
{
"books_3": {
"mappings": {
"properties": {
"book_title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"book_author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
in this case, when you put A* as a value for your wildcard query you won't get any results back because both book_title and book_author use standard analyzer for the text field and all uppercased characters are removed from indexed tokens - for this configuration elasticsearch won't store any tokens starting with A, see below
GET _analyze
{
"analyzer": "standard",
"text": "Test"
}
{
"tokens" : [
{
"token" : "test",
"start_offset" : 0,
"end_offset" : 4,
"type" : "<ALPHANUM>",
"position" : 0
}
]
}
You can set case_insensitive to true in your wildcard query and that will fix your issue as docs say
case_insensitive [7.10.0]Added in 7.10.0. (Optional, Boolean) Allows
case insensitive matching of the pattern with the indexed field values
when set to true. Default is false which means the case sensitivity of
matching depends on the underlying field’s mapping.
<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"
}
]
},
I am new to JSON. I have a JSON list in a tree structure like below:
{
"complaint#simulator.amazonses.com": {
"time": "2018-01-02T20:45:46.65Z",
"type": "Complaint",
"bounceType": "null",
"bounceSubType": "null"
},
"struax#example.org": {
"time": "2018-01-02T20:53:03Z",
"type": "Bounce",
"bounceType": "Permanent",
"bounceSubType": "Suppressed"
},
"bounce-test#service.socketlabs.com": {
"time": "2018-01-02T21:06:40.097Z",
"type": "Bounce",
"bounceType": "Permanent",
"bounceSubType": "Suppressed"
},
"bounce#simulator.amazonses.com": {
"time": "2018-01-02T21:08:02Z",
"type": "Bounce",
"bounceType": "Permanent",
"bounceSubType": "General"
},
"jstrechay#example.org": {
"time": "2018-01-05T06:31:39Z",
"type": "Bounce",
"bounceType": "Permanent",
"bounceSubType": "General"
},
"leematt45#example.org": {
"time": "2018-01-05T06:49:13Z",
"type": "Bounce",
"bounceType": "Permanent",
"bounceSubType": "Suppressed"
},
"afbweb#example.org": {
"time": "2018-01-07T12:50:38Z",
"type": "Bounce",
"bounceType": "Transient",
"bounceSubType": "General"
},
"bajanina2013#example.org": {
"time": "2018-01-02T08:12:19Z",
"type": "Bounce",
"bounceType": "Transient",
"bounceSubType": "MailboxFull"
},
"martin.bunt#example.org": {
"time": "2018-01-05T07:00:24Z",
"type": "Complaint",
"bounceType": "null",
"bounceSubType": "null"
}
}
My SQL table columns are Email, time, type, bounceType, and bounceSubType.
How can I extract data from the JSON list and save it in the DB?
I am using this code:
string JSON = response.Content.ReadAsStringAsync().Result;
var jObj = (JObject)JsonConvert.DeserializeObject(JSON);
The JSON is in a tree structure and I am not able to fetch the parent node and the respective child in a list.
Here is what I would do. First, define a model class to hold the item data (you might already have such a class):
class BounceItem
{
public string Email { get; set; }
public DateTime Time { get; set; }
public string Type { get; set; }
public string BounceType { get; set; }
public string BounceSubType { get; set; }
}
Next, deserialize the JSON into a Dictionary<string, BounceItem>:
var dict = JsonConvert.DeserializeObject<Dictionary<string, BounceItem>>(json);
The email addresses will become the keys in the dictionary, and values will be BounceItem objects containing the nested properties. However, notice that the Email property in each BounceItem will not be populated at this point.
To fix that, post-process the dictionary to copy each key into the Email property on the corresponding item, storing results into a List<BounceItem>:
var list = dict.Select(kvp => { kvp.Value.Email = kvp.Key; return kvp.Value; }).ToList();
Now you have a list of model objects which should match up to your SQL table, and you can insert them using whatever method is appropriate for your database of choice.
Fiddle: https://dotnetfiddle.net/5rzyCs
It's pretty simple using Json.NET or using Newtonsoft.Json.Linq, if you are using c#.NET.
First Method:
dynamic jsonObject = JsonConvert.DeserializeObject("your json string");
Second Method:
dynamic jsonObject = JObject.Parse("your json string");
After parsing you can pass the jsonObject to the DB.
You need to create a class based on your Json Responce. Than from that class deserialize your object like this
Class1 class1Object = JsonConvert.DeserializeObject<Class1>(str)
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/