If I have a simple JSON object that is written in the html document space under a script tag (that looks like below), how do I easily load it into Silverlight? I need to load each of the two arrays below into their own String[] in .NET, and it doesn't need to be dynamic as to what arrays in the Player object it loads, it will always just be those two.
Thanks!!!
Player = {
Names: ["name 1","name 2","name 3"],
Files: ["file 1","file 2","file 3"]
}
In Pseudo code:
String[] Names = Page.Javascript.Player.Names;
String[] Files = Page.Javascript.Player.Files;
Try this regex:
Player[^;,N]+Names ?: ?(\[[^\]]*\])[^F]+Files ?: ?(\[[^\]]*\])
This regual expression will match for the string above. The result groups 1 and 2 will contain your json array with the strings of Names and Files`. Check also this fiddle.
The next step is just to drop the two groups in a json parser or another regular expression and you have your strings.
If you have more Json to parse, you can use .Net Json helpers in System.Json dll
var jsonObj = (JsonObject)JsonArray.Parse("{ Names: ['name 1','name 2','name 3'], Files: ['file 1','file 2','file 3']}");
// You need to cast JsonValue in string
string[] names = (jsonObj["Names"] as JsonArray).Select(j => (string)j).ToArray();
string[] files = (jsonObj["Files"] as JsonArray).Select(j => (string)j).ToArray();
You can use DataContractJsonSerializer to convert Json in object...
See more http://msdn.microsoft.com/fr-fr/library/cc197957(v=vs.95).aspx
Related
i have a string variable which receives data from web the data is in the from of string like this
string output="[1,2,3,4,5,6,7,8,9,0]";
i want to convert it into a string array [] so that i can specify each element via for each loop
string output;
into
string[] out;
PS: if any predefined method is there that will also help
You can do that using Trim And Split:
var out = output.TrimStart('[').TrimEnd(']').Split(',');
But your data looks like JSON string. So, if you are dealing with JSON instead of making your own parser try using libraries that already does that such as JSON.NET.
You can use Trim functions to remove brackets and then use Split() function to get the string array that contains the substrings in this string that are delimited by elements of a specified Unicode character.
var res = output.TrimStart('[')
.TrimEnd(']')
.Split(',');
string[] arr = output.Where(c => Char.IsDigit(c)).Select(c => c.ToString()).ToArray();
output.Substring(1, output.Length - 2).Split(',');
How can i convert this string from asp hidden filed
"[['Q458','','100','85'],['Q459','TS','90','65'],['Q460','','80','15']]"
to two dimensional array in C#
i have tried .ToArray() and didn't work
You can use a String.Split() method to create the first level of arrays, then go through that array and call Split() again.
Your first delimiter is ],[ and the second one is just ,.
You will have to remove the initial [ and the final one manually ] in all arrays (both levels).
Try deserializing using JavaScriptSerializer:
var arr = hiddenField.Value;
//"[['Q458','','100','85'],['Q459','TS','90','65'],['Q460','','80','15']]" ;
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var strArray = ser.Deserialize<string[][]>(arr);
Array is now 2D string Array with values like:
'Q458','','100','85'
'Q459','TS','90','65'
'Q460','','80','15'
I will receive an response in the form of JSON string.
We have an existing tool developed in C# which will take input in XML format.
Hence i am converting the JSON string obtained from server using Newtonsoft.JSON to XML string and passing to the tool.
Problem:
When converting JSON response to XML, I am getting an error
"Failed to process request. Reason: The ' ' character, hexadecimal
value 0x20, cannot be included in a name."
The above error indicates that the JSON Key contains a space [For Example: \"POI Items\":[{\"lat\":{\"value\":\"00\"}] which cannot be converted to XML element.
Is there any approach to identify spaces only JSON key's ["POI Items"] and remove the spaces in it?
Also suggest any alternative solution so that we needn't change the existing solution?
Regards,
Sudhir
You can use Json.Net and replace the names while loading the json..
JsonSerializer ser = new JsonSerializer();
var jObj = ser.Deserialize(new JReader(new StringReader(json))) as JObject;
var newJson = jObj.ToString(Newtonsoft.Json.Formatting.None);
.
public class JReader : Newtonsoft.Json.JsonTextReader
{
public JReader(TextReader r) : base(r)
{
}
public override bool Read()
{
bool b = base.Read();
if (base.CurrentState == State.Property && ((string)base.Value).Contains(' '))
{
base.SetToken(JsonToken.PropertyName,((string)base.Value).Replace(" ", "_"));
}
return b;
}
}
Input : {"POI Items":[{"lat":{"value":"00","ab cd":"de fg"}}]}
Output: {"POI_Items":[{"lat":{"value":"00","ab_cd":"de fg"}}]}
I recommend using some sort of Regex.Replace().
Search the input string for something like:
\"([a-zA-Z0-9]+) ([a-zA-Z0-9]+)\":
and then replace something like (mind the missing space):
\"(1)(2)\":
The 1st pair of parenthesis contain the first word in a variable name, the 2nd pair of parenthesis means the 2nd word. The : guarantees that this operation will be done in variable names only (not in string data). the JSON variable names are inside a pair of \"s.
Maybe it's not 100% correct but you can start searching by this.
For details check MSDN, and some Regex examples
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx
I need to tokenize JSON arrays to convert them into an Object[,].
The format will be something like:
[[1,"2"],[",]",5]
which would translate into
string json = #"[[1,""2""],["",]"",5]]";
for the matrix:
1 "2"
",]" 5
What would be the easiest way to tokenize this in C# since splitting will not work as the string may contain the split character (but escaped)?
Using Json.Net
string json = #"[[1,""2""],["",]"",5]]";
var arr = JsonConvert.DeserializeObject<object[][]>(json);
or using JavaScriptSerializer
var arr = new JavaScriptSerializer().Deserialize<object[][]>(json);
I'm trying to use System.Text.RegularExpressions.Regex class to grab some text from a JSON string. The sting is something like
[{"name":"joe","message":"hello","sent":"datetime"}{"name":"steve","message":"bye","sent":"datetime"}]
I'm attempting to use the Matches() method to grab the "message" values. However, specifying a match as something like message":"*","sent as the pattern would return 3 matches:
hello
bye
hello","sent":"datetime"}{"name":"steve","message":"bye
How do I structure the options or modify my pattern to exclude recursive regex checks? I only want matches
hello
bye
The JavaScriptSerializer class (namespace System.Web.Script.Serialization, assembly System.Web.Extensions.dll) is pretty useful for dealing with JSON strings like this.
var json = "[{\"name\":\"joe\",\"message\":\"hello\",\"sent\":\"datetime\"},{\"name\":\"steve\",\"message\":\"bye\",\"sent\":\"datetime\"}]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<object[]>(json);
// now have an array of objects, each of which happens to be an IDictionary<string, object>
foreach(IDictionary<string, object> map in result)
{
var messageValue = map["message"].ToString();
Console.WriteLine("message = {0}", messageValue);
}
JSON is better parsed by a JSON tool.
You can try using the non-greedy syntax .*? for example.