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)
Related
I want to my all json array size is equal,suppose my array limit is 2, in my json many array have less or high json count than 2.if array object size less than 2 add empty array with null values and if greater than 2 remove.
{
"data": {
"getUsers": [
{
"UserProfileDetail": {
"UserStatus": {
"name": "User One"
},
"UserStatusDate": "2018-10-31T06:12:42+00:00",
"EnrollId": "am**********************************",
"lastDate": "2019-07-22T03:05:39.0245313-04:00"
},
"UserInformation": {
"Id": 1111122,
"firstName": "*****",
"middleName": null,
"lastName": "*****",
"otherNames": null,
"primaryState": "MA",
"otherState": [
"MA",
"BA",
"DL",
"RJ"
],
"UserLicense": [
{
"licenseState": "MA",
"licenseNumber": "000000000",
"licenseStatus": null,
"aaaaaaaaaaaaaaaaa": "only one"
},
{
"licenseState": "MA2",
"licenseNumber": "0000000002",
"licenseStatus": null,
"aaaaaaaaaaaaaaaaa": "only one2"
},
{
"licenseState": "MA3",
"licenseNumber": "0000000003",
"licenseStatus": null,
"aaaaaaaaaaaaaaaaa": "only one3"
}
],
"UserLocation": [
{
"location": "DL",
"SubrLocation": [
{
"sub location1": "DL1",
"sub location2": "DL2"
}
]
}
],
"Setting": "ADMINISTRATIVE",
"primaryEmail": "*****#*****.com",
"modifiedAt": null,
"createdAt": null
}
},
{
"UserProfileDetail": {
"UserStatus": {
"name": "User Two"
},
"UserStatusDate": "2019-10-31T06:12:42+00:00",
"EnrollId": "am**********************************",
"lastDate": "2019-07-22T03:05:39.0245313-04:00"
},
"UserInformation": {
"Id": 443333,
"firstName": "*****",
"middleName": "Jhon",
"lastName": "*****",
"otherNames": null,
"primaryState": "AK",
"otherState": [
"MP",
"CLT"
],
"UserLicense": [
{
"licenseState": "KL",
"licenseNumber": "000000220",
"licenseStatus": "Valid"
}
],
"UserLocation": [
{
"location": "KL",
"SubrLocation": [
{
"sub location1": "KL",
"sub location2": "KL2"
},
{
"sub location1": "TN",
"sub location2": "TN2"
}
]
}
],
"Setting": "ADMINISTRATIVE",
"primaryEmail": "*****#*****.com",
"modifiedAt": null,
"createdAt": null
}
}
]
}
}
The above example following array object is found.
1.UserLicense
2.UserLocation
3.SubrLocation
The 'UserLicense' location in first json is 3 and second json is two. I want remove one from first json and add empty json to second. like this i want all json array (including nested json array object).
I know its not a correct requirement/method.
some body please help me
This is a generic question about working with json in .NET.
Option 1
You could create a class model that represents your json, then load it with JsonConvert.DeserializeObject, then make the changes in the model and serialize it back to json with JsonConvert.SerializeObject.
The top two elements would look like this:
public class TopElement
{
[JsonProperty("data", NullValueHandling = NullValueHandling.Ignore)]
public Data Data { get; set; }
}
public class Data
{
[JsonProperty("getUsers", NullValueHandling = NullValueHandling.Ignore)]
public GetUsers[] GetUsers { get; set; }
}
// ... and so on
Deserialize json from string:
var obj = JsonConvert.DeserializeObject<TopElement>(jsonString);
Option 2
You could use directly JObject to load the json and then make changes in it.
I am serializing an anonymous object to use as a request message for an HTTP post request. The problem is that one of the JSON keys contains a dot in its name. VS throws out ''invalid anonymous type member declarator'' error.
return JsonConvert.SerializeObject(new
{
query = "something",
firstname.keyword = "xyz"
});
What can I do to solve this issue?
Edit: the real json request looks something like this, so I don't think I can use a dictionary:
{
"query": {
"bool": {
"must": [
{
"term": {
"firstname.keyword": ""
}
}
],
"must_not": [ ],
"should": [ ]
}
},
"from": 0,
"size": 10,
"sort": [ ],
"aggs": { }
}
Json can generally be represented using arrays, dictionaries and anonymous objects.
The first part of your Json can be generated as follows:
return JsonConvert.SerializeObject(new
{
query = new
{
#bool = new
{
must = new[]
{
new
{
term = new Dictionary<string, object>
{
["firstname.keyword"] = string.Empty,
}
}
}
}
}
});
I'm trying to understand why JSON.Net will modify the original JObject (formSchema) in two cases below where I'm adding JArray and JObject
to objects I've defined as vars.
I assume the two vars I created were standalone objects in their own right but it appears they are not.
In the first case, requiredItems is a JArray var, in which I want to add the token "certification" to formSchema, but I've placed the Add method
on requiredItems. Not formSchema.
In the second case, I add certifyProperty to formSchema using the Add method on consentProps. The property handily gets added to formSchema
without a direct reference to it.
Why is this? Are they linked in memory? Where in the JSON.Net docs is this explained? I cannot find it.
namespace JSONProps
{
class Program
{
static void Main(string[] args)
{
string jsonSchema = #"
{
""jsonSchema"": {
""type"": ""object"",
""title"": ""a title"",
""properties"": {
""consent"": {
""type"": ""object"",
""title"": ""Consent of Applicant"",
""required"": [
""applicantConsent""
],
""properties"": {
""applicantConsent"": {
""type"": ""boolean"",
""title"": ""I give my Consent"",
},
}
}
}
}
}
";
// First case
var formSchema = JObject.Parse(jsonSchema);
var requiredProps = formSchema["jsonSchema"]["properties"]["consent"]["required"] as JArray;
requiredProps.Add("certification");
// Second case
var consentProps = formSchema["jsonSchema"]["properties"]["consent"]["properties"] as JObject;
var certifyProperty = JObject.Parse(#" { ""type"" : ""boolean"", ""title"" : ""This is true."" } ");
consentProps.Add("certification", certifyProperty);
Console.WriteLine(formSchema.ToString());
}
}
}
$ dotnet run
{
"jsonSchema": {
"type": "object",
"title": "a title",
"properties": {
"consent": {
"type": "object",
"title": "Consent of Applicant",
"required": [
"applicantConsent",
"certification"
],
"properties": {
"applicantConsent": {
"type": "boolean",
"title": "I give my Consent"
},
"certification": {
"type": "boolean",
"title": "This is true."
}
}
}
}
}
}
In my app, I'm getting some data in a string format, which I'm converting to json:
string stringValue = System.Text.Encoding.Default.GetString(message.Value);
var jsonValue = JsonConvert.DeserializeObject(stringValue);
The resulting json string looks like this:
[
{
"LOCATION_ID": 2800,
"CITY": "Sao Paulo"
},
{
"LOCATION_ID": 1700,
"CITY": "Seattle"
},
{
"LOCATION_ID": 2300,
"CITY": "Singapore"
},
{
"LOCATION_ID": 1600,
"CITY": "South Brunswick"
},
{
"LOCATION_ID": 1500,
"CITY": "South San Francisco"
},
{
"LOCATION_ID": 1400,
"CITY": "Southlake"
},
{
"LOCATION_ID": 2600,
"CITY": "Stretford"
},
{
"LOCATION_ID": 2200,
"CITY": "Sydney"
}
]
What syntax can I use to iterate over this json array, and print out one json object at a time?
What syntax can I use to iterate over this json array, and print out
one json object at a time?
Define a model:
public class MyModel
{
public int LOCATION_ID { get; set; }
public string CITY { get; set; }
}
and then deserialize to this model:
var models = JsonConvert.DeserializeObject<IList<MyModel>>(stringValue);
and now you are free to iterate with standard C# iteration constructs like the foreach keyword:
foreach (MyModel model in models)
{
Console.WriteLine(model.LOCATION_ID);
Console.WriteLine(model.CITY);
}
The easiest way is to use dynamics as follows.
Note, this method reduces code footprint and is more readable the alternative approaches:
var json = #"[
{
'LOCATION_ID': 2800,
'CITY': 'Sao Paulo'
},
{
'LOCATION_ID': 1700,
'CITY': 'Seattle'
}
]";
dynamic parsedArray = JsonConvert.DeserializeObject(json);
foreach (dynamic item in parsedArray)
Debug.WriteLine($"Location ID: {item.LOCATION_ID} City: {item.CITY}");
Darin Dimitrov is spot on answer.
Another alternative, if you don't really want strongly model, is using Dictionary and its qualities.
var jsonObj = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(stringValue);
foreach (var obj in jsonObj)
{
Console.WriteLine("{0}: {1}", obj["LOCATION_ID"], obj["CITY"]);
}
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>()