Creating JSON out of string - c#

I want to get JSON similar to this
{
"Name": "xxxxx",
"ApplicationId": "xxxxx",
"Features": [
{
"Name": "xxxxx",
"Code": "xxxxx",
}
]
}
and my code is so far is
var json = JsonConvert.SerializeObject(
new {
Name = name ,
ApplicationId = applicationID ,
Features = (new[]{feature_name , feature_code})
}, Formatting.None);
I can not figure out the feature part, it won't get created as in the example.
I read so many post, but did not find anything about inner objects.

You didn't give the features appropriate names, hence then variable names are used.
Use this instead:
new[] { new { Name = feature_name, Code = feature_code } }
Also, you have to supply a list of features, for example using LINQ.
features.Select(f => new { Name = f.feature_name, Code = f.feature_code })

Another way of doing this can be like:
var createJson = new {
Name = "xxxxx",
ApplicationId = "xxxxx",
Features = new[] {
new { Name = "xxxxx", Code = "xxxxx" },
new { Name = "xxxxx", Code = "xxxxx" }
}
};
var json = JsonConvert.SerializeObject(createjson, Formatting.Indented);

Related

How can I easily create readable JSON objects in C# .Net Core similar to JavaScript

In JavaScript I can easily create an object and assign variables with some very basic notation such as:
const Object = JSON.parse('
{
"something": outsideVariable,
"someArray": [
"hey",
"there"
]
}
');
Is there a simple way to do this with C# that is clean and easy to assign variables too? I experimented a bit with the JsonObject but the code for that looks needlessly messy, for example:
JsonObject jsonPayload = new JsonObject
{
["documentId"] = documentID,
["testMode"] = true,
["signers"] = new JsonArray
{
new JsonObject
{
["label"] = "John Smith",
["contactMethod"] = new JsonArray
{
new JsonObject
{
["type"] = "link"
}
}
}
}
};
I also tried using the literal symbol (#) with a string, but it ends up injecting carriage returns and linefeeds, and inserting variables winds of being a great deal of concatination.
IMHO , the most close you want is this
var jsonPayload = new
{
documentId = 1,
testMode = true,
signers = new object[]
{
new {
label="John Smith",
contactMethod= new object[]
{
new {
type="link"
}
}
}
}
};
and code
var json= System.Text.Json.JsonSerializer
.Serialize(jsonPayload,new JsonSerializerOptions { WriteIndented = true });
//or if you need
var jsonParsed= JsonDocument.Parse(json);
result
{
"documentId": 1,
"testMode": true,
"signers": [
{
"label": "John Smith",
"contactMethod": [
{
"type": "link"
}
]
}
]
}

Parse nested json and return the values as string[]

Can you help me parse the values in 'realEstateProperties' attribute (ex. serial number and economyType.value). Here is a part of the json file:
{
"Entity1": {
"id": "5f514d20744a1fb",
"realEstateProperties": [
{
"serialNumber": "11",
"cadastralSections": [
{
"id": "5f514dc11a1e3",
"economyType": {
"value": "landRegisterPage.type",
}
}
],
"landRegisterPage": {
"id": "3456",
"landRegisterBook": {
"abbreviation": null
},
"note": "LRP",
"tags": null
},
"propertyTextBlock": null
}
],
"customFields": [],
Here is what I currently have:
public static string[] GetJsonValues(string jsonProperty)
{
testCaseName = "Entity1";
FixtureIncident.Root incObject = new FixtureIncident.Root();
incObject = LoadJSONFile();
JObject incJson = JObject.FromObject(incObject);
var attributes = incJson[testCaseName].ToList<JToken>();
var property = attributes.Find(i => i.ToObject<JProperty>().Name == jsonProperty) as JArray; //returns property=null
string[] Properties = property.ToObject<string[]>();
return Properties;
}
property returns null and I am not sure how to correct it.
I need to save all the realEstateProperties values in a string[].
I found some similar topics but I couldn't adjust my code so I make it works. Thanks in advance for your help.

What's the syntax to create an object that is an array of objects with JObject?

I'm creating a database seeder for Cosmos DB (a document or JSON based DB). Some of the C# models have a property Config that is JSON so I've been using this type of code to set that property:
Config = JObject.FromObject(new { })
which works as does actually setting property(ies) inside the object:
Config = JObject.FromObject(new
{
contextOptionSource = "$.domains.governmentEntityType_active"
}),
However, I can't figure out how to set Config to an array of objects. I tried actually using C# Models thinking that JObject would convert them for me like so:
Config = JObject.FromObject(
new List<Question>
{
new Question
{
Key = "contact",
Label = "Contact Person",
HelpText = "",
Config = JObject.FromObject(new {}),
Type = "text",
ContextTarget = "$.data.contact"
},
new Question
{
Key = "company",
Label = "Company Name",
HelpText = "",
Config = JObject.FromObject(new {}),
Type = "text",
ContextTarget = "$.data.company"
}
}),
This compiled OK but when I run I get a runtime error "Object serialized to Array. JObject instance expected.'" Am I wrong to think that JObject should convert the C# models to JSON? If they have to be generic objects that's fine but I can't get the syntax right that the FromObject method will accept multiple objects inside this Config property.
Edit: Here's the JSON I'm trying to produce:
"config": {
"questions": [{
"key": "contact",
"label": "Contact Person",
"helpText": "Contact Person",
"config": {},
"type": QuestionKind.Textbox,
"contextTarget": "$.data.contact",
"enabledRule": null,
"validationRules": [],
"visibleRule": null
},
{
"key": "company",
"label": "Company Name",
"helpText": "Company Name",
"config": {},
"type": QuestionKind.Textbox,
"contextTarget": "$.data.company",
"enabledRule": null,
"validationRules": [],
"visibleRule": null
}]
}
Try JToken or JArray.
var Config = JToken.FromObject(
new List<Question>
{
new Question
{
Key = "contact",
Label = "Contact Person",
HelpText = "",
Config = JObject.FromObject(new {}),
Type = "text",
ContextTarget = "$.data.contact"
},
new Question
{
Key = "company",
Label = "Company Name",
HelpText = "",
Config = JObject.FromObject(new {}),
Type = "text",
ContextTarget = "$.data.company"
}
}
);
var result = Config.ToString();
The result is:
[
{
"Label": "Contact Person",
"HelpText": "",
"Type": "text",
"ContextTarget": "$.data.contact",
"Config": {},
"Key": "contact"
},
{
"Label": "Company Name",
"HelpText": "",
"Type": "text",
"ContextTarget": "$.data.company",
"Config": {},
"Key": "company"
}
]
You need to know what type of JToken you want to create. For example, you can create a JObject either from a string value or from a .NET object. They are like factory methods. For example, if you want to create it from List<string>, you will have to tell the framework you will be creating a JArray from an in memory object:
var fromArray = JArray.FromObject(new List<string>
{
"One",
"Two"
});
Or that you will be creating JObject:
var fromObj = JObject.FromObject(new Customer() { Name = "Jon" });
Or you can create the tokens from JSON:
var fromJson = JArray.Parse("[\"One\", \"Two\"]");
Finally, you can just create JToken which is the parent of all the above classes (JArray, JObject) but then you will only have access to JToken properties and methods:
var Config = JToken.FromObject(
new List<string>
{
"One",
"Two"
});
See this for the various tokens.
so the C# code I needed to do so was:
Config = JObject.FromObject(new
{
questions = JArray.FromObject(
new List<Question>
{
new Question
{
Key = "contact",
Label = "Contact Person",
HelpText = "",
Config = emptyJObject,
Type = "text",
ContextTarget = "$.data.contact"
},
new Question
{
Key = "company",
Label = "Company Name",
HelpText = "",
Config = emptyJObject,
Type = "text",
ContextTarget = "$.data.company"
}
})
})
Use JArray, you can pick the constructor best suited for your needs here

JSON data in PUT request in C#

I am trying to make a PUT request with a C# client, this request has JSON data in it.
I use this, which I got from here: Passing values to a PUT JSON Request in C#
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
reg_FirstName = "Bob",
reg_LastName = "The Guy"
});
Ofcourse, the Json string looks like this:
{
"reg_FirstName":"Bob",
"reg_LastName":"The Guy"
}
But how would I go around creating a JSON string like this:
{
"main": {
"reg_FirstName": "Bob",
"reg_LastName": "The Guy"
},
"others": [
{
"reg_FirstName": "Robert",
"reg_LastName": "The Guy"
},
{
"reg_FirstName": "Rob",
"reg_LastName": "The Guy"
}
]
}
You can use the same way - dynamic objects, so in your case it would look like this:
var serializer = new JavaScriptSerializer();
string json =
serializer.Serialize(
new {
main = new
{
reg_FirstName = "Bob",
reg_LastName = "The Guy"
},
others = new[]
{
new { reg_FirstName = "Bob", reg_LastName = "The Guy" },
new { reg_FirstName = "Bob", reg_LastName = "The Guy" }
}
}
);

Create nested json with c#

I am able to create a flat serialized JSON string pretty easily with c#
My issue is I want to create a nested string like this below
[ {
title: "Yes",
id : "1",
menu: [ {
title: "Maybe",
id : "3",
alert : "No",
menu: [ {
title: "Maybe Not",
id : "8",
alert : "No",
menu: []
} ]
} ]
},
{
title: "No",
id : "2",
menu: []
}]
Any help would be great
Are you using MVC 3? - Do something like:
return Json(myObectWithListProperties, JsonRequestBehavior.AllowGet);
I use this to return complex C# objects that match the structure of the JavaScript objects I want.
e.g.:
var bob = new {
name = "test",
orders = new [] {
new { itemNo = 1, description = "desc" },
new { itemNo = 2, description = "desc2" }
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
gives:
{
"name": "test",
"orders": [
{
"itemNo": 1,
"description": "desc"
},
{
"itemNo": 2,
"description": "desc2"
}
]
}
EDIT: A bit more nesting for fun:
var bob = new {
name = "test",
orders = new [] {
new { itemNo = 1, description = "desc" },
new { itemNo = 2, description = "desc2" }
},
test = new {
a = new {
b = new {
something = "testing",
someOtherThing = new {
aProperty = "1",
another = "2",
theThird = new {
bob = "quiteDeepNesting"
}
}
}
}
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
gives:
{
"name": "test",
"orders": [
{
"itemNo": 1,
"description": "desc"
},
{
"itemNo": 2,
"description": "desc2"
}
],
"test": {
"a": {
"b": {
"something": "testing",
"someOtherThing": {
"aProperty": "1",
"another": "2",
"theThird": {
"bob": "quiteDeepNesting"
}
}
}
}
}
}
Try using
using System.Web.Script.Serialization;
//Assumed code to connect to a DB and get data out using a Reader goes here
Object data = new {
a = reader.GetString(field1),
b = reader.GetString(field2),
c = reader.GetString(field3)
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(data);
This is built-in and saves you the work of serializing to JSON yourself!
This example assumes you are getting data from a database using some sort of reader, and it then constructs the object you want to serialize using an anonymous class. Your anonymous class can be as simple or complex as you need it to be and the JavaScriptSerializer will handle transforming it to JSON. This approach is also useful because you can easily control the JSON property names it will create in the JSON.
using System.Web.Script.Serialization;
var strNJson = new
{
to = "hello",
notification = new
{
title = "textTitle",
body = "bodyText"
}
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(strNJson);
{ "to":"hello",
"notification": {
"title":"titleText",
"body":"bodyText"
}
}
You can make use of the ExpandoObject under the System.Dynamic namespace.
Here is a small snippet for achieving your solution:
dynamic parameters = new dynamic[2];
parameters[0] = new ExpandoObject();
parameters[0].title = "Yes";
parameters[0].id = "1";
parameters[0].menu = new dynamic[1];
parameters[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].title = "Maybe";
parameters[0].menu[0].id = "3";
parameters[0].menu[0].alert = "No";
parameters[0].menu[0].menu = new dynamic[1];
parameters[0].menu[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].menu[0].title = "Maybe Not";
parameters[0].menu[0].menu[0].id = "8";
parameters[0].menu[0].menu[0].alert = "No";
parameters[0].menu[0].menu[0].menu = new dynamic[0];
parameters[1] = new ExpandoObject();
parameters[1].title = "No";
parameters[1].id = "2";
parameters[1].menu = new dynamic[0];
string json = JsonConvert.SerializeObject(parameters, Formatting.Indented);
Console.WriteLine(json);
Here is the work in fiddle
Note: There are other ways to achieve this, but I have been using this approach.

Categories

Resources