urlencoded values to Model - c#

so I have a url encoded string which I managed to convert to json using
Request.InputStream.Position = 0;
var inputStream = new StreamReader(Request.InputStream);
var json = inputStream.ReadToEnd();
var dict = HttpUtility.ParseQueryString(json);
var json3 = new JavaScriptSerializer().Serialize(
dict.Keys.Cast<string>()
.ToDictionary(k => k, k => dict[k]));
then I eventually converted it to a dynamic object, however what I would like to do is convert some of the properties to a collection of models. Are there any methods out there that would allow me to achieve the case below without having to write my own routine:
this is what json3 looks like:
> {
"inserted[0].Property1":"dsdsdsds","inserted[0].Property2":"323","inserted[1].Property1":"dsds",
"inserted[1].Property2":"","inserted[1].Property3":"32",
"updated[0].ID":"1","updated[0].Property3":"7",
"updated[1].ID":"2","updated[1].Property3":"7","updated[1].Property4":"78",
"page":"1","size":"10","orderBy":"","groupBy":"","filter":"","aggregates":""
}
So I would like to get this and convert all the keys that starts with inserted[0] to a Model that we can call SomeClass that has Property1, Property2, ... Property4 esentially ending up with a List, same goes for all the keys that start with updated[x].
Thanks,

Related

how to convert a string with equal "=" sign to json in c#

I have following string, this returns from the web service
"Status=Success,PNR=76UUEI78787870,Customer_Ref=89511133545"
I want to convert this in to json like below
{
"Status": "Success",
"PNR": "76UUEI78787870",
"Customer_Ref": "89511133545"
}
how can I do that.
var str = "Status=Success,PNR=76UUEI78787870,Customer_Ref=89511133545";
var vals = str.Split(',');
var json = "{" +
string.Join(",",
vals.Select(val => val.Split('=')).Select(s => string.Format("\"{0}\": \"{1}\"", s[0], s[1]))) +
"}";
Try this code that uses JavaScriptSerializer:
var paramList = "Status=Success,PNR=76UUEI78787870,Customer_Ref=89511133545";
var dict = paramList.Split(',').Select(x => x.Split('=')).ToDictionary(x => x[0], x => x[1])
var json = new JavaScriptSerializer().Serialize(dict);
It handles things like quotes inside names properly.
This might do the trick for you
private static string format_json(string json)
{
json = json.Replace('=',":");
dynamic parsedJson = JsonConvert.DeserializeObject(json);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
This would work with newtonsoft.Json and json.net library
You could convert a given string to Dictionary and serialize using Json.Net as below.
string s = #"Status=Success,PNR=76UUEI78787870,Customer_Ref=89511133545";
var dictionary = s.Split(',') // create a dictionary.
.Select(x=>x.Split('='))
.ToDictionary(x=>x[0], x=>x[1]);
string json = JsonConvert.SerializeObject( dictionary, new KeyValuePairConverter( ) );
//output
// {"Status":"Success","PNR":"76UUEI78787870","Customer_Ref":"89511133545"}
Check this fiddle
Consider working with StringBuilder (specially if performance is important and if you need to work with bigger strings in the future).
string sourceString = "Status=Success,PNR=76UUEI78787870,Customer_Ref=89511133545";
StringBuilder bufferString = new StringBuilder();
bufferString.Append("{\"").Append(sourceString)
.Replace(",", "\",\"")
.Replace("=", "\": \"")
.Append("\"}");
string outputString = bufferString.ToString();
/*
* libraries like Newtonsoft.Json NuGet package could help prettify the output string if needed
*/
string prettyJSON = JValue.Parse(bufferString.ToString()).ToString(Formatting.Indented);
Note: This consistently outperform the use of the string methods.

Read Json object and put the values in a List of string

Platform: C#
IDE: Visual Studio 2010
I am trying to read all the values from json object and put it in the list of string , for which I am doing Json deserialize but it throws me error...
Here is what I have tried
List<string> lstPName = new List<string>();
JavaScriptSerializer strJsonSer = new JavaScriptSerializer();
localhost.Pstats objStats = new localhost.Pstats();
var strJson = objStats.GetAutoCompleteData(txtSearchBox.Text.Trim());
lstPName = strJsonSer.DeserializeObject<string>(strJson);
Here is what the Json object holds
[{"PlayerName":"WA Mota"},{"PlayerName":"Atif Ahmed"}]
So, I need the player name value to be added in the list...
Simple and straightforward solution:
var strJson = "[{\"PlayerName\":\"WA Mota\"},{\"PlayerName\":\"Atif Ahmed\"}]";
var strJsonSer = new JavaScriptSerializer();
var list = new List<string>();
var result = strJsonSer.DeserializeObject(strJson) as object[];
if (result != null)
{
foreach (Dictionary<string, object> x in result)
{
list.Add(x["PlayerName"].ToString());
}
}
Or, if you are preferring LINQ - you can use instead of foreach loop something like:
list = result
.Cast<Dictionary<string, object>>()
.Select(x => x["PlayerName"].ToString())
.ToList();
Key idea: DeserializeObject used for parsing JSON data like yours gives you array of Dictionary<string, object> where key is JSON property name and value is JSON property value. Size of array equals to objects count in your JSON data.

How do I Deserialize the following JSON string with the .NET JavaScriptSerializer class?

I have the following JSON object:
[{"newValue":"{\"id\":\"1\",\"desc\":\"description\"}",
"oldValue":"{\"id\":\"2\",\"desc\":\"description2\"}"}]
newValue is holds the new values for the object I want to deserialize into and oldValue contains the old values for the object I want to deserialize into, but I am not sure how to deserialize each one individually or can it be done together?
Your json is a little bit weird, since the value of newValue and oldValue is string, not object. It seems that they are double-serialized. Below code works (by first deserializing the whole json string, and then the old/new/values)
var jArr = JArray.Parse(json);
var anon = new { id = 0, desc = "" };
var items = jArr.Select(item => new
{
NewValue = JsonConvert.DeserializeAnonymousType(item["newValue"].ToString(),anon),
OldValue = JsonConvert.DeserializeAnonymousType(item["oldValue"].ToString(),anon)
})
.ToList();

How to turn String (json-like) into Object

In my controller, I get a string that is JSON:
String json_string = this.Request.Content.ReadAsStringAsync().Result;
That looks something like so:
{
"21": {"Id":21,"DisplayOrder":3, ... snip ... },
"333":{"Id":333,"DisplayOrder":2, ... snip ... },
"591":{"Id":591,"DisplayOrder":1, ... snip ... }
}
I don't have a say in the structure of this JSON so can't format it into something without keys. They keys aren't necessary since the ID is within the Value of that Dictionary.
In any case, how do I convert json_string in such a way that allows me to pull out the only two items I want when I iterate over the 'rows' in that structure... Id, DisplayOrder?
Like so:
int Id = row_item.Id;
int DisplayOrder = row_item.DisplayOrder;
Thanks!
Eric
string json = #"{
""21"": {""Id"":21,""DisplayOrder"":3},
""333"":{""Id"":333,""DisplayOrder"":2},
""591"":{""Id"":591,""DisplayOrder"":1}}";
var list = new JavaScriptSerializer()
.Deserialize<Dictionary<string, Dictionary<string, object>>>(json)
.Values
.ToList();
Console.WriteLine(list[0]["Id"]); // <--21
You can also do the same thing with Json.Net
var jObj = JsonConvert
.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(json)
.Values
.ToList();
Console.WriteLine(jObj[0]["Id"]);
dynamic can be utilized too
var jObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json)
.Values
.ToList();
Console.WriteLine(jObj[0].DisplayOrder);

How to deserialize currencies list from openexchangerates.org to C# custom class or object?

I need to get currency values list in C# from here:
http://openexchangerates.org/currencies.json
which produces this kind of output:
{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
"AMD": "Armenian Dram",
"ANG": "Netherlands Antillean Guilder",
"AOA": "Angolan Kwanza"
// and so on
}
I managed to get a string containing values above using C#, but I cannot find a way to deserialize that string into any custom class or anonymous object, so I am wondering how to do that?
Also, I am trying to use Json.NET to do that, but so far couldn't find a solution...
using Json.Net
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
--EDIT--
You can make it shorter
WebClient w = new WebClient();
string url = "http://openexchangerates.org/currencies.json";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(w.DownloadString(url));
A solution using only .Net 4.0 and no third party libraries:
string url = "http://openexchangerates.org/currencies.json";
var client = new System.Net.WebClient();
string curStr = client.DownloadString(url);
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var res = (js.DeserializeObject(curStr) as Dictionary<string, object>)
.Select(x => new { CurKey = x.Key, Currency = x.Value.ToString() });
Outputs a list of anonymous objects with the keys and values from the list as properties.
Enjoy :)

Categories