Passing Array from Javascript to C# - c#

I have a .js script that contain an array:
The output of the js is like:
var foo=
[
{
"bar1":"value1",
"bar2":"value2"
// And so on...
}
]
I have no access to the js source, so i cannot output as JSON and Deserialize.
I can only get this as a String using WebClient, but how i can parse it and create an Array/Dictionary and work on it inside C#?

You should consider calling WebClient.DownloadString . Then Parse using JSON.Net or whatever
As per the example provided over there
string json = #"{
""Name"": ""Apple"",
""Expiry"": "2008-12-28T00:00:00",
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small

var foo = new JavaScriptSerializer().Deserialize<List<YourModelHere>>(YourString);

You can use a JavaScriptSerializer to deserialize that string:
string str=
#"var foo =
[
{
""bar1"":""value1"",
""bar2"":""value2""
}
]";
JavaScriptSerializer js = new JavaScriptSerializer();
var o = js.Deserialize<Dictionary<string,string>[]>(str.Substring(str.IndexOf('[')));
Result:
Dictionary<String,String> (2 items)
Key Value
------ --------
bar1 value1
bar2 value2

Related

how to add an empty array to a json payload?

Is it possible to add an array to a json payload?
For example, let's say this is my payload:
string json = #"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': [{'something':'awesome'},{'a':'b'}],
'item': [],
'nested':[{'upgrademe':'please'}, {'upgrademe':'no'}]
}
}";
The result I'd like would be something like this:
string json = #"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': [{'something':'awesome'},{'a':'b'}],
'item': [],
'nested':[{'upgrademe':'please', 'emptyArray':[]}, {'upgrademe':'no'}]
}
}";
For every channel.nested where upgrademe == please then I'd like to add an empty array like [].
before:
'nested':[{'upgrademe':'please'}, {'upgrademe':'no'}]
after:
'nested':[{'upgrademe':'please', 'emptyArray':[]}, {'upgrademe':'no'}]
My current implementation:
public static JObject AddArray(this JObject jObject, string path, string key, string value)
{
var obs = jObject.SelectToken(path);
if (obs == null)
{
return jObject;
}
foreach (var jsonObject in obs)
{
if (jsonObject.SelectToken(key).ToString().ToLower() != value.ToLower())
{
continue;
}
jObject.SelectToken(path).Parent.AddAfterSelf(new JValue(new JProperty("emptyArray", new JArray())));
}
return jObject;
}
I'm getting an exception on this line:
usage example:
var result = jobject.AddArray("channel.nested", "upgrademe", "please");
the above says the following:
find the object "channel.nested" and when upgrademe==please, add a sibbling node as an empty array
How do we conditionally add an array object to a json payload?
Since you're adding a new property into an object. You don't need to use JValue
Just use JProperty directly:
AddAfterSelf(new JProperty("emptyArray", new JArray()))

C# Json to List

I have a json object as follows:
"dnsNames": {
"type": "array",
"defaultValue": [
"something.else.com",
"something.com",
"else.com"
]
}
I'd like to read that into a List<string> the same way I can read it into a string (i.e. without creating a class for it):
JObject jsonParameters = JObject.Parse(File.ReadAllText(filePath));
string test = jsonParameters["parameters"]["dnsNames"]["defaultValue"].ToString();
Just unsure if that's possible or what the syntax for it might be.
Navigate the object structure as you see it dnsNames.defaultValue then convert that object to a given type (List<string> in our case):
var json =
#"{""dnsNames"": {
""type"": ""array"",
""defaultValue"": [
""something.else.com"",
""something.com"",
""else.com""
]
}}";
var jObject = JObject.Parse(json);
var list = jObject["dnsNames"]["defaultValue"].ToObject<List<string>>();
// ?list
// Count = 3
// [0]: "something.else.com"
// [1]: "something.com"
// [2]: "else.com"

how to parse 3 level nested array using newtonsoft json

I have the following json which is in geojson format, and Id like to be able to parse this into a nested list in c#:
public IList<IList<IList<double>>> Coordinates { get; set; }
"coordinates": [
[
[-3.213338431720785, 55.940382588499197],
[-3.213340490487523, 55.940381867350276],
[-3.213340490487523, 55.940381867350276],
[-3.213814166228732, 55.940215021175085],
[-3.21413960035129, 55.940100842843712]
]
]
I have tried the following but I get an exception:
var node = jsonProperties["geometry"]["coordinates"].Values();
var coordinates = node.Select(x=>x.Value<List<double>>());
Exception detail:
Cannot cast Newtonsoft.Json.Linq.JArray to
Newtonsoft.Json.Linq.JToken.
To deserialize using newtonsoft. Create Foo class with a coordinates property, inclose the JSON script with curly brackets to denote it as an object then call JsonConvert.DeserializeObject<Foo>(Json).
private class Foo
{
public List<List<List<double>>> coordinates { get; set; }
}
var json = #"{
coordinates: [
[
[-3.213338431720785, 55.940382588499197],
[-3.213340490487523, 55.940381867350276],
[-3.213340490487523, 55.940381867350276],
[-3.213814166228732, 55.940215021175085],
[-3.21413960035129, 55.940100842843712]
]
]
}";
var result = JsonConvert.DeserializeObject<Foo>(json);
May not be exactly what you want but using dynamic type I could access the values. For example this sample code
class Program
{
static void Main(string[] args)
{
string sampleJson = #"{ ""coordinates"": [
[
[-3.213338431720785, 55.940382588499197],
[-3.213340490487523, 55.940381867350276],
[-3.213340490487523, 55.940381867350276],
[-3.213814166228732, 55.940215021175085],
[-3.21413960035129, 55.940100842843712]
]
]}";
dynamic d = JObject.Parse(sampleJson);
Console.WriteLine(d.coordinates[0].Count);
foreach (var coord in d.coordinates[0])
{
Console.WriteLine("{0}, {1}", coord[0], coord[1]);
}
Console.ReadLine();
}
displays the following:
5
-3.21333843172079, 55.9403825884992
-3.21334049048752, 55.9403818673503
-3.21334049048752, 55.9403818673503
-3.21381416622873, 55.9402150211751
-3.21413960035129, 55.9401008428437
I suggest you to parse them into something more suitable like List<Tuple<double, double>> though there is also solution for nested lists. Please check my inline comments:
const string json = #"
{
""coordinates"":
[
[
[-3.213338431720785, 55.940382588499197],
[-3.213340490487523, 55.940381867350276],
[-3.213340490487523, 55.940381867350276],
[-3.213814166228732, 55.940215021175085],
[-3.21413960035129, 55.940100842843712]
]
]
}";
var jsObject = JObject.Parse(json);
/*
* 1. Read property "coordinates" of your root object
* 2. Take first element of array under "coordinates"
* 3. Select each pair-array and parse their values as doubles
* 4. Make a list of it
*/
var result = jsObject["coordinates"]
.First()
.Select(pair => new Tuple<double, double> (
pair[0].Value<double>(),
pair[1].Value<double>()
)
).ToList();
And for List<List<List<double>>> please see #YTAM answer.

How to get JSON values into a string array?

I am using VS2010 with C# 4. I have JSON similar to the following:
{"ItemDetails":{"Item":{"val": [
{"Description":"Desk1","Amount":"100.00"},
{"Description":"Desk2","Amount":"200.00"},
{"Description":"Desk3","Amount":"300.00"}]}}}
I want to get all the amount values into one string array like what is shown below:
amount={100.00,200.00,300.00}
How could I implement this? Do I have to loop through the JSON object or is there another way to do this?
I would recommend using NewtonSofts JSON library, but another (yet ugly) way is to use Regular Expressions.
var json = "{\"ItemDetails\":{\"Item\":{\"val\": [ " +
"{\"Description\":\"Desk1\",\"Amount\":\"100.00\",}," +
"{\"Description\":\"Desk2\",\"Amount\":\"200.00\",}," +
"{\"Description\":\"Desk3\",\"Amount\":\"300.00\"}}}";
// What I think you want
var amount = Regex.Matches(json, "Amount\":\"(.*?)\"").Cast<Match>().Select(m => m.Groups[1].Value).ToArray();
// Values 'converted' to json
var jsonAmount = "amount={" + string.Join(",", amount) + "}";
Using Json.Net you can do this with a LINQ-to-JSON query:
string json = #"
{
""ItemDetails"": {
""Item"": {
""val"": [
{
""Description"": ""Desk1"",
""Amount"": ""100.00""
},
{
""Description"": ""Desk2"",
""Amount"": ""200.00""
},
{
""Description"": ""Desk3"",
""Amount"": ""300.00""
}
]
}
}
}";
JToken token = JToken.Parse(json);
string[] amounts = token.SelectToken("ItemDetails.Item.val")
.Children()
.Select(t => t["Amount"].ToString())
.ToArray();
Console.WriteLine("amount={" + string.Join(",", amounts) + "}");
Output:
amount={100.00,200.00,300.00}
I am assuming you are not using JSON.NET. If this the case, then you can try it.
It has the following features -
LINQ to JSON
The JsonSerializer for quickly converting your .NET objects to JSON and back again
Json.NET can optionally produce well formatted, indented JSON for debugging or display
Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized
Ability to convert JSON to and from XML
Supports multiple platforms: .NET, Silverlight and the Compact Framework
Look at the example below.
In this example, JsonConvert object is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj) and DeserializeObject(String json) -
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject(json);

Generate JSON object with NewtonSoft in a single line

I'm using the JSON library NewtonSoft to generate a JSON string:
JObject out = JObject.FromObject(new
{
typ = "photos"
});
return out.ToString();
Output:
{
"typ": "photos"
}
My question:
Is it possible to get the output in a single line like:
{"typ": "photos"}
You can use the overload of JObject.ToString() which takes Formatting as parameter:
JObject obj = JObject.FromObject(new
{
typ = "photos"
});
return obj.ToString(Formatting.None);
var json = JsonConvert.SerializeObject(new { typ = "photos" }, Formatting.None);
Here's a one-liner to minify JSON that you only have a string for:
var myJson = "{\"type\" :\"photos\" }";
JObject.Parse(myJson).ToString(Newtonsoft.Json.Formatting.None)
Output:
{"type":"photos"}
I'm not sure if this is what you mean, but what I do is this::
string postData = "{\"typ\":\"photos\"}";
EDIT:
After searching I found this on Json.Net:
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
and maybe you could use the info on this website.
But I'm not sure, if the output will be on one line... Good luck!
If someone here who doesn't want to use any external library in MVC, they can use the inbuilt System.Web.Script.Serialization.JavaScriptSerializer
One liner for that will be:
var JsonString = new JavaScriptSerializer().Serialize(new { typ = "photos" });

Categories

Resources