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"}
Related
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);
I have no problem deserializing a single json object
string json = #"{'Name':'Mike'}";
to a C# anonymous type:
var definition = new { Name = ""};
var result = JsonConvert.DeserializeAnonymousType(json, definition);
But when I have an array:
string jsonArray = #"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";
I am stuck.
How can it be done?
The solution is:
string json = #"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";
var definition = new[] { new { Name = "" } };
var result = JsonConvert.DeserializeAnonymousType(json, definition);
Of course, since result is an array, you'll access individual records like so:
string firstResult = result[0].Name;
You can also call .ToList() and similar methods on it.
You can deserialize to dynamic object by this.
dynamic result = JsonConvert.DeserializeObject(jsonArray);
One approach is to put an identifier in your JSON array string.
This code worked for me:
var typeExample = new { names = new[] { new { Name = "" } } };
string jsonArray = #"{ names: [{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]}";
var result = JsonConvert.DeserializeAnonymousType(jsonArray, typeExample);
I am implementing a utility method to convert queryString to JsonString.
My code is as follows:
public static string GetJsonStringFromQueryString(string queryString)
{
var nvs = HttpUtility.ParseQueryString(queryString);
var dict = nvs.AllKeys.ToDictionary(k => k, k => nvs[k]);
return JsonConvert.SerializeObject(dict, new KeyValuePairConverter());
}
when I test with the following code:
var postString = "product[description]=GreatStuff" +
"&product[extra_info]=Extra";
string json = JsonHelper<Product>.GetJsonStringFromQueryString(postString);
I got
{
"product[description]":"GreatStuff",
"product[extra_info]":"Extra",
...
}
what I would like to get is
{
"product":{
"description": "GreatStuff",
"extra_info" : "Extra",
...
}
}
How can I achieve this without using System.Web.Script Assembly? (I am on Xamarin and have no access to that library)
You need to remove the product[key] (excepting the product property name or key...) part to get what you want...
That is, you should pre-process your query string before parsing it this way:
string queryString = "product[description]=GreatStuff" +
"&product[extra_info]=Extra";
var queryStringCollection = HttpUtility.ParseQueryString(queryString);
var cleanQueryStringDictionary = queryStringCollection.AllKeys
.ToDictionary
(
key => key.Replace("product[", string.Empty).Replace("]", string.Empty),
key => queryStringCollection[key]
);
var holder = new { product = cleanQueryStringDictionary };
string jsonText = JsonConvert.SerializeObject(holder);
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.
I need to create a Json object dynamically by looping through columns.
so declaring an empty json object then add elements to it dynamically.
eg:
List<String> columns = new List<String>{"FirstName","LastName"};
var jsonObj = new {};
for(Int32 i=0;i<columns.Count();i++)
jsonObj[col[i]]="Json" + i;
And the final json object should be like this:
jsonObj={FirstName="Json0", LastName="Json1"};
[TestFixture]
public class DynamicJson
{
[Test]
public void Test()
{
dynamic flexible = new ExpandoObject();
flexible.Int = 3;
flexible.String = "hi";
var dictionary = (IDictionary<string, object>)flexible;
dictionary.Add("Bool", false);
var serialized = JsonConvert.SerializeObject(dictionary); // {"Int":3,"String":"hi","Bool":false}
}
}
I found a solution very similar to DPeden, though there is no need to use the IDictionary, you can pass directly from an ExpandoObject to a JSON convert:
dynamic foo = new ExpandoObject();
foo.Bar = "something";
foo.Test = true;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
and the output becomes:
{ "FirstName":"John", "LastName":"Doe", "Active":true }
You should use the JavaScriptSerializer. That can Serialize actual types for you into JSON :)
Reference: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
EDIT: Something like this?
var columns = new Dictionary<string, string>
{
{ "FirstName", "Mathew"},
{ "Surname", "Thompson"},
{ "Gender", "Male"},
{ "SerializeMe", "GoOnThen"}
};
var jsSerializer = new JavaScriptSerializer();
var serialized = jsSerializer.Serialize(columns);
Output:
{"FirstName":"Mathew","Surname":"Thompson","Gender":"Male","SerializeMe":"GoOnThen"}
Using dynamic and JObject
dynamic product = new JObject();
product.ProductName = "Elbow Grease";
product.Enabled = true;
product.StockCount = 9000;
Console.WriteLine(product.ToString());
// {
// "ProductName": "Elbow Grease",
// "Enabled": true,
// "StockCount": 9000
// }
Or how about:
JObject obj = JObject.FromObject(new
{
ProductName = "Elbow Grease",
Enabled = true,
StockCount = 9000
});
Console.WriteLine(obj.ToString());
// {
// "ProductName": "Elbow Grease",
// "Enabled": true,
// "StockCount": 9000
// }
https://www.newtonsoft.com/json/help/html/CreateJsonDynamic.htm