Reputation: 1576
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#?
Upvotes: 0
Views: 791
Reputation: 152501
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
Upvotes: 0
Reputation: 2908
var foo = new JavaScriptSerializer().Deserialize<List<YourModelHere>>(YourString);
Upvotes: 0
Reputation:
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
Upvotes: 1