Partial copy of dynamic object in c# - c#

As you can see below, in the json i have "data", "data2" and invoice.
My goal is to split a json file in more parts that have "data" and "data2" and a part of "invoice".
I've de-serialized the string, that contain the json code, in a dynamic object so i need to make a partial copy of this in a temp dynamic object, serialize it and than continue my job.
string strJsonOuput = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlInput);
dynamic objComune = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(strJsonOuput);
This an example of the json:
{
"data": {
"a": "1",
"b": "2"
},
"data2": {
"something1": {
"thing1": "xxx",
},
"Invoice": [
{
"head": "bbb",
"body": {
"argument1":"aaa"
}
}
{
"head": "xxxx",
"body": {
"argument2": "ccc"
}
}
{
"head": "xxxx",
"body": {
"argument2": "ccc"
}
}
{...}
]
}
}

Related

How to serialise a list of objects of different type with Newtonsoft.Json?

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"
}
}
]
}
]
}

C# Parsing JSON Object

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);

How to add Values into Json array to set equal array size

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.

How to declare anonymous type for Json serialization, if one of the Json keys contains a dot?

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,
}
}
}
}
}
});

Why does JSON.Net modify the original JObject?

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."
}
}
}
}
}
}

Categories