Converting string to JArray - c#

I have to use an API that expects a string containing a an array of json objects.
internal string InitConnect( string RequestData )
{
try
{
dynamic filejsonJarray = new JArray();
filejsonJarray = JArray.Parse(RequestData);
JObject jsonObject = (JObject)filejsonJarray.First;
if (jsonObject.ContainsKey("IP_ADDRESS".ToUpper()))
{
...
}
}
}
In my code I tried different ways of calling this API but don't seem to be able to get the argument right. I have to create an object (connData) using data I have read from a config file (sJSONConfig) and use it as an argument to API; last thing I tried:
string sJSONConfig = Global.ReadJsonConfig();
// returns"{\r\n \"Name\": \"BLAH\",\r\n \"IPAddress\": \"1.2.3.4\",\r\n \"Port\": \"5880\"\r\n}"
JArray filejsonJarray = new JArray();
JObject jsonObject = new JObject();
jsonObject = JObject.Parse(sSJONConfig);
//filejsonJarray = JArray.Parse(sSJONConfig);
//jsonObject = (JObject)filejsonJarray.First;
// Reconnect using new config data
var connData = new
{
NAME = jsonObject.Property("Name").Value.ToString(),
IP_ADDRESS = jsonObject.Property("IPAddress").Value.ToString(),
PORT = jsonObject.Property("Port").Value.ToString(),
Enabled = "true",
Something = "false"
};
string reqData = JsonConvert.SerializeObject(filejsonJarray);
//filejsonJarray.Add(reqData);
InitConnect(reqData);
Obviously, I cannot changed the InitConnect API.

You can create your desired JSON like this:
string sJSONConfig = Global.ReadJsonConfig();
JObject jsonObject = JObject.Parse(sJSONConfig);
JObject connData = new JObject(
new JProperty("NAME", jsonObject["Name"]),
new JProperty("IP_ADDRESS", jsonObject["IPAddress"]),
new JProperty("PORT", jsonObject["Port"]),
new JProperty("Enabled", "true"),
new JProperty("Something", "false")
);
JArray filejsonJarray = new JArray(connData);
string reqData = filejsonJarray.ToString();
InitConnect(reqData);

Related

How to add fields to JSON object without them existing?

I have a JObject that I am trying to add fields to in a way like this:
JObject dataObject = new JObject();
dataObject[currentSection][key] = val;
currentSection, key and val are all strings, I want it so when its all serialized at the end that it looks something like this:
{
"currentSection": {
"key": "value"
}
}
How would I go about doing this?
You can use JObject.Add() method to add a property to JObject.
Create a JObject for the nested object.
Add property to the nested object.
Add property with nested object to root JObject.
JObject dataObject = new JObject();
JObject nestedObj = new JObject();
nestedObj.Add(key, val);
dataObject.Add(currentSection, nestedObj);
Demo # .NET Fiddle
You have one nested json object inside of the another one. So you have to create a nested currentSection json object before assigning a key to currrentSection
string currentSection = "currentSection";
string key = "key";
string val = "val";
JObject dataObject = new JObject();
dataObject[currentSection] = new JObject();
dataObject[currentSection][key] = val;
or you can do the same in one line
var dataObject = new JObject { [currentSection] = new JObject { [key] = val } };
json
var json = dataObject.ToString();
{
"currentSection": {
"key": "val"
}
}

Unserialize JSON string

I have this code
string jsonString = "{\r\n \"value1\":\"value2\" \r\n}";
string normalString = "value4";
NameValueCollection collection = new NameValueCollection();
collection["First"] = jsonString;
collection["Second"] = normalString;
var nvcDictionary = collection.AllKeys.ToDictionary(k => k, k => collection[k]);
var result = JsonConvert.SerializeObject(nvcDictionary);
which produces
{\"First\":\"{\\r\\n \\\"value1\\\":\\\"value2\\\" \\r\\n}\",\"Second\":\"value4\"}
but I want it like this
{\"First\":\"{\"value1\":\"value2\"}\",\"Second\":\"value4\"}
I have tried
Regex.Unescape(jsonString);
and
jsonString = jsonString.Replace("\r\n", "");
jsonString = jsonString.Replace("\\", "");
but I cant seem to "unserialize" the jsonString in the beginning
not exactly what I wanted but I will solve it like this
string jsonString = "{\r\n \"value1\":\"value2\" \r\n}";
string normalString = "value4";
var parsedJson = JObject.Parse(jsonString);
string valuefromJsonString = parsedJson["value1"].ToString();
NameValueCollection collection = new NameValueCollection();
collection["First"] = valuefromJsonString;
collection["Second"] = normalString;
var nvcDictionary = collection.AllKeys.ToDictionary(k => k, k => collection[k]);
var result = JsonConvert.SerializeObject(nvcDictionary);
which produces
{\"First\":\"value2\",\"Second\":\"value4\"}
Why don't you remove the Newlines before you process?
string jsonString = "{\r\n \"value1\":\"value2\" \r\n}";
jsonString = jsonString.Replace(Environment.NewLine, "");
When I run that, the result has a value of
"{\"First\":\"{ \\\"value1\\\":\\\"value2\\\" }\",\"Second\":\"value4\"}"
If your intention is to convert the json string to a dictionary, you can deserialize your string to a dictionary using JsonConvert.Deserialize<T>() method and then create a new dictionary based on that.
string jsonString = "{\r\n \"value1\":\"value2\" \r\n}";
string normalString = "value4";
Dictionary<string, string> dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
Dictionary<string, string> newDict = new Dictionary<string, string>()
{
{ "First", dict["value1"] },
{ "Second", normalString }
};
Console.WriteLine(JsonConvert.SerializeObject(newDict));
// Prints:
{"First":"value2","Second":"value4"}

JObject nested property

I am trying to make a json object like this with JObject:
{
"input": {
"webpage/url": "http://google.com/"
}
}
I can add properties like:
JObject job = new JObject(
new JProperty("website/url", "http://www.google.com") );
But any time I try to nest an object inside another object so I can have the parent "input" it throws an exception.
How do you make nested properties with JObject?
Probably the most straightforward way would be:
var input = new JObject();
input.Add("webpage/url", "http://google.com");
var obj = new JObject();
obj.Add("input", input);
Which gives you:
{
"input": {
"webpage/url": "http://google.com"
}
}
Another way would be:
var input = new JObject
{
{ "webpage/url", "http://google.com" }
};
var obj = new JObject
{
{ "input", input }
};
... Or if you wanted it all in one statement:
var obj = new JObject
{
{
"input",
new JObject
{
{ "webpage/url", "http://google.com" }
}
}
};
Just carry on as you are, and nest them in another level:
JObject job = new JObject(
new JProperty("website/url", "http://www.google.com") );
JObject parent = new JObject(new JProperty("input", job));
parent.ToString() now gives:
{ "input": {
"website/url": "http://www.google.com" } }

serialize object to json .NET

I have to serialize object to json string. This is my code:
var addData = new {
nick = user.UserName,
imie = user.Firstname,
nazwisko = user.Surname,
wojewodztwo = user.State
};
var tempUser = new
{
email = user.Email,
list = "12212",
state = 1,
confirm = 0,
custom_fields = addData
};
(...)
var serializer = new JavaScriptSerializer();
PostData = serializer.Serialize(tempUser);
This is result:
"{\"email\":\"testowy#aa.pl\",\"list\":\"12212\",\"state\":1,\"confirm\":0,\"custom_fields\":{\"nick\":\"JakisNicvk\",\"imie\":\"Marian\",\"nazwisko\":\"Mariański\",\"wojewodztwo\":\"małopolskie\"}}"
It looks awfull. How can I generate json string like this, without \? (and where main object has array with custom_fields)?
{"email":"22#aa.pl","list":"12212","custom_fields":{"personalization_tag_1":"value
1","personalization_tag_2":"value 2"}}
Regards.

Using JSON.NET to add a boolean property

I have this JSON data
{
"extensions": {
"settings" : {
"extension1": {
"property1": "value 1",
"property2": "value 2"
}
}
}
}
my goal is to add a new boolean property using JSON.NET to look like this
{
"extensions": {
"settings" : {
"extension1": {
"property1": "value 1",
"property2": "value 2",
"bool_property": true
}
}
}
}
I only have this code and I'm stuck with AddAfterSelf and AddBeforeSelf
string pref = "path_of_the_preferences_file";
string _pref = string.empty;
using (StreamReader reader = new StreamReader(pref, Encoding.UTF8))
{
_pref = reader.ReadToEnd();
}
// REFORMAT JSON.DATA
JObject json = JObject.Parse(_pref);
var extension1 = json["extensions"]["settings"]["extension1"];
How do I insert the new boolean property "bool_property" ?
Thanks
A JObject is essentially a dictionary. Just get a reference to the object you wish to add the property to and add it.
var propertyName = "bool_property";
var value = true;
var obj = JObject.Parse(json);
var extension1 = obj.SelectToken("extensions.settings.extension1") as JObject;
if (extension1 != null)
{
extension1[propertyName] = value;
}
If you're targeting .NET 4 and up, you know the structure of the json and the name of the property you wish to add, you can use dynamic here.
var value = true;
dynamic obj = JObject.Parse(json);
obj.extensions.settings.extension1.bool_value = value;
You can even mix and match.
var propertyName = "bool_property";
var value = true;
dynamic obj = JObject.Parse(json);
obj.extensions.settings.extension1[propertyName] = value;
Deserialize your JSON, add a property and serialize it back into a string.
dynamic sourceJson = JsonConvert.DeserializeObject(json, typeof(object));
sourceJson.extensions.settings.extension1.bool_property = false;
var modifiedJson = JsonConvert.SerializeObject(sourceJson, Formatting.Indented);
I got it
string pref = "path_of_the_preferences_file";
string _pref = string.empty;
using (StreamReader reader = new StreamReader(pref, Encoding.UTF8))
{
_pref = reader.ReadToEnd();
}
// REFORMAT JSON.DATA
JObject json = JObject.Parse(_pref);
var extension1 = json["extensions"]["settings"]["extension1"];
var a = extension1.Children();
JProperty cond_it = null;
foreach (var b in a)
{
if (b.ToString().ToLower().Contains("cond_it"))
{
cond_it = (JProperty)b;
break;
}
}
if (cond_it != null)
{
var b = cond_it.Value.SelectToken("location").Parent;
b.AddAfterSelf(new JProperty("blacklist", true));
}

Categories

Resources