json string creation with c# - c#

I am creating a string variable to use in an rest post call and it is failing. when I debug and look at the json value I am told it is not in json format. It sure seems to be key:value pairs so I an not sure what the issue here is?
instead of double single quotes I also tried escaping the " by using \ like so (neither method is good it seems):
//string postData = "{\"title\":\"Change Title\", \"description\":\"Create description\", \"scheduledStartDate\": \"2018-12-24T11:24:48.91Z\", \"scheduledEndDate'': ''2018-12-25T11:24:48.91Z'' }";
string postData = #"{''changeNumberForClone'': ''C03688051'',
''scheduledStartDate'': ''2017-12-24T11:24:48.91Z'',
''scheduledEndDate'': ''2017-12-25T11:24:48.91Z''}";

Using NewtonSoft Json.NET, you could use the following code to obtain a correct json string:
Dictionary<String, String> jsonDict = new Dictionary<String, String>();
jsonDict.Add("changeNumberForClone", "C03688051");
jsonDict.Add("scheduledStartDate", "2017-12-24T11:24:48.91Z");
jsonDict.Add("scheduledEndDate", "2017-12-25T11:24:48.91Z");
String postData = JsonConvert.SerializeObject(jsonDict);
If you don't want to add a new library to your project:
String postData = "{\"changeNumberForClone\":\"C03688051\", \"scheduledStartDate\":\"2017-12-24T11:24:48.91Z\", \"scheduledEndDate\": \"2017-12-25T11:24:48.91Z\"}";
In order to produce json strings with multiple levels of depth using the same approach, you can use anonymous objects as follows:
var obj = new { abc = new { def = new { one="1", two="2" } } };
var json = JsonConvert.SerializeObject(obj);
or, if you prefer to use Dictionary instances:
var obj = new Dictionary<String,Object>()
{
{
"abc", new Dictionary<String,Object>()
{
{
"def" , new Dictionary<String,Object>()
{
{ "one", "1" }, {"two", "2" }
}
}
}
}
};
the output, for both approaches, would be the following:
{
"abc": {
"def" : {
"one": "1",
"two": "2",
},
}
}

Related

.NET 6 “core” Create Dynamic Object containing List<MyOtherDynamicListObject> [duplicate]

For some of my unit tests I want the ability to build up particular JSON values (record albums in this case) that can be used as input for the system under test.
I have the following code:
var jsonObject = new JObject();
jsonObject.Add("Date", DateTime.Now);
jsonObject.Add("Album", "Me Against The World");
jsonObject.Add("Year", 1995);
jsonObject.Add("Artist", "2Pac");
This works fine, but I have never really like the "magic string" syntax and would prefer something closer to the expando-property syntax in JavaScript like this:
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
Well, how about:
dynamic jsonObject = new JObject();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against the world";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
You can use the JObject.Parse operation and simply supply single quote delimited JSON text.
JObject o = JObject.Parse(#"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
This has the nice benefit of actually being JSON and so it reads as JSON.
Or you have test data that is dynamic you can use JObject.FromObject operation and supply a inline object.
JObject o = JObject.FromObject(new
{
channel = new
{
title = "James Newton-King",
link = "http://james.newtonking.com",
description = "James Newton-King's blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
Json.net documentation for serialization
Neither dynamic, nor JObject.FromObject solution works when you have JSON properties that are not valid C# variable names e.g. "#odata.etag". I prefer the indexer initializer syntax in my test cases:
JObject jsonObject = new JObject
{
["Date"] = DateTime.Now,
["Album"] = "Me Against The World",
["Year"] = 1995,
["Artist"] = "2Pac"
};
Having separate set of enclosing symbols for initializing JObject and for adding properties to it makes the index initializers more readable than classic object initializers, especially in case of compound JSON objects as below:
JObject jsonObject = new JObject
{
["Date"] = DateTime.Now,
["Album"] = "Me Against The World",
["Year"] = 1995,
["Artist"] = new JObject
{
["Name"] = "2Pac",
["Age"] = 28
}
};
With object initializer syntax, the above initialization would be:
JObject jsonObject = new JObject
{
{ "Date", DateTime.Now },
{ "Album", "Me Against The World" },
{ "Year", 1995 },
{ "Artist", new JObject
{
{ "Name", "2Pac" },
{ "Age", 28 }
}
}
};
There are some environment where you cannot use dynamic (e.g. Xamarin.iOS) or cases in where you just look for an alternative to the previous valid answers.
In these cases you can do:
using Newtonsoft.Json.Linq;
JObject jsonObject =
new JObject(
new JProperty("Date", DateTime.Now),
new JProperty("Album", "Me Against The World"),
new JProperty("Year", "James 2Pac-King's blog."),
new JProperty("Artist", "2Pac")
)
More documentation here:
http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm
Sooner or later you will have property with a special character. e.g. Create-Date. The hyphen won't be allowed in property name. This will break your code. In such scenario, You can either use index or combination of index and property.
dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use
Simple way of creating newtonsoft JObject from Properties.
This is a Sample User Properties
public class User
{
public string Name;
public string MobileNo;
public string Address;
}
and i want this property in newtonsoft JObject is:
JObject obj = JObject.FromObject(new User()
{
Name = "Manjunath",
MobileNo = "9876543210",
Address = "Mumbai, Maharashtra, India",
});
Output will be like this:
{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}
May I suggest using the nameof expression combined with a model for the structure you're trying to build?
Example:
record RecordAlbum(string Album, string Artist, int Year);
var jsonObject = new JObject
{
{ nameof(RecordAlbum.Album), "Me Against The World" },
{ nameof(RecordAlbum.Artist), "2Pac" },
{ nameof(RecordAlbum.Year), 1995 }
};
As an added benefit to removing the "magic string" aspect - this also will give you a little bit of refactor-ability. You can easily rename any given property name for the record and it should update the value returned by the nameof() expression.
You can use Newtonsoft library and use it as follows
using Newtonsoft.Json;
public class jb
{
public DateTime Date { set; get; }
public string Artist { set; get; }
public int Year { set; get; }
public string album { set; get; }
}
var jsonObject = new jb();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(jsonObject );

How to create JSON object in C#

I need to create JSON like this:
{
"files": [
{
"file_path": "example.txt",
"content" : "source code \n with multiple lines\n"
}
]
}
But my code (I serialized it to JSON later) doesn't correspond to this example above
var requestBody = new
{
files = new string[] { snippet.FileName, snippet.Content }
};
Can someone help me :)?
EDIT:
my serialization method:
protected string serializeToJson( object obj )
{
return JsonConvert.SerializeObject( obj, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() } );
}
Try That:
using System.Text.Json;
var obj = new
{
files = new[]
{
new
{
file_path = "example.txt",
content ="source code \n with multiple lines\n"
}
}
};
var json = JsonSerializer.Serialize(obj);
Console.WriteLine(json);
Result:
We can make use of the serializeobject to convert into json
string jsonStr = JsonConvert.SerializeObject(obj);
This method will be available in the newtonsoft package

JObject in C# for independent data fetching of JSON

I am using Json.Net to parse my JSON
This is my JSON:
"OptionType": {
"C": [
"C",
"Call"
],
"P": [
"P",
"Put"
]
}
Before this step, when processed, as a result, I would get a value from any of this.
For example Option Type: Call
Whatever value I get, I need it to be transcodified according to the above JSON.
Example: Option Type: C
First of all your sample data is not a valid JSON. You need to wrap it to the curvy braces.
If your sample is a part of the JSON object, you can map OptionType to the Dictionary<string, List<string>>.
To find valid option you will need to iterate this dictionary like in the sample below:
var valueToCheck = "Call";
string type = null;
foreach (var kvp in optionTypes)
{
if (kvp.Value.Contains(valueToCheck))
{
type = kvp.Key;
break;
}
}
Same using JObject with fixed JSON data:
var json = #"{
""OptionType"":{
""C"": [
""C"",
""Call""
],
""P"": [
""P"",
""Put""
]
}
}";
var valueToCheck = "Call";
string type = null;
var ot = JObject.Parse(json);
var objectType = ot["OptionType"];
foreach (var token in objectType)
{
var prop = token.ToObject<JProperty>();
var key = prop.Name;
var values = prop.Value.ToObject<List<string>>();
if (values.Contains(valueToCheck))
{
type = key;
break;
}
}
Code is not perfect but it is just an idea what to do.
You need to iterate over properties of JObject and then search your option type and then replace your search option with its parent key.
This is custom function can do above task.
public static JObject GetJObject(JObject jObject, List<string> optionType)
{
foreach (var type in jObject["OptionType"])
{
var key = type.ToObject<JProperty>().Name;
var values = type.ToObject<JProperty>().Value.ToObject<List<string>>();
foreach (var option in optionType)
{
if (values.Contains(option))
{
int index = values.IndexOf(option);
values.RemoveAt(index);
values.Insert(index, key);
}
}
JToken jToken = JToken.FromObject(values);
jObject.SelectToken("OptionType." + key).Replace(jToken);
}
return jObject;
}
And you can use above custom function this like
string json = File.ReadAllText(#"Path to your json file");
JObject jObject = JObject.Parse(json);
List<string> optionType = new List<string> { "Call", "Put" };
JObject result = GetJObject(jObject, optionType);
Output:

JSON Serialize array returns NULL in JSON string

I am building a JSON model like this
JObject issue_model = JObject.FromObject(new
{
labels = new[] { "import", "automation"}
}
below code for serialization
string request_json = JsonConvert.SerializeObject(issue_model,
Newtonsoft.Json.Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
But when i try to build this from a dynamic list of values like
list<string> lp_list = new list<string>();
//lp_list contains a list of string values
string[] lp_labels = lp_list.ToArray();
JObject issue_model = JObject.FromObject(new
{
labels = jira_labels
}
I got the JSON as
"labels": [
[
null,
null
]
]
But i am expecting this json as
"labels" : { "import", "automation"}
How can i make the array serialization right way
I modified your code in a console Application.
List<string> lp_list = new List<string>();
lp_list.Add("import");
lp_list.Add("automation");
//lp_list contains a list of string values
//string[] lp_labels = lp_list.ToArray();
JObject issue_model = JObject.FromObject(new
{
labels = lp_list
});
Console.WriteLine(issue_model);
The result is as follows:
Hope it answers your question.

Customizing the JSON received from Web API

I need to add one more node to Json string.
Following is the code from where I am reading the data.
var url = "https://xyz_12232_abc/0908978978979.json";
var sys = new WebClient();
var content = sys.DownloadString(url);
I received following output from above code:
{
"2312312312313":
{
"emailId":"abc#gmail.com",
"model":"XYZ001",
"phone":"+654784512547",
"userName":"User1"
},
"23456464512313":
{
"emailId":"abcd#gmail.com",
"model":"XYZ002",
"phone":"+98745114474",
"userName":"User2"
},
"45114512312313":
{
"emailId":"abcde#gmail.com",
"model":"XYZ3",
"phone":"+214784558741",
"userName":"User3"
}
}
But, I want this output like below:
{
"Records": [
{
"UID":"2312312312313":,
"emailId":"abc#gmail.com",
"model":"XYZ001",
"phone":"+654784512547",
"userName":"User1"
},
{
"UID":"23456464512313":,
"emailId":"abcd#gmail.com",
"model":"XYZ002",
"phone":"+98745114474",
"userName":"User2"
},
{
"UID":"45114512312313":,
"emailId":"abcde#gmail.com",
"model":"XYZ3",
"phone":"+214784558741",
"userName":"User3"
}
]
}
Now, how can it be achieved ?
You can use Json.NET to massage the data into your desired output:
var jsonStr = #"..."; // your JSON here
var obj = JsonConvert.DeserializeObject<Dictionary<string, JObject>>(jsonStr);
var formattedObj = new
{
Records = obj.Select(x =>
{
x.Value.AddFirst(new JProperty("UID", x.Key));
return x.Value;
})
};
// serialize back to JSON
var formattedJson = JsonConvert.SerializeObject(formattedObj);

Categories