Convert JS array string to C# List - c#

I have a js stringify array "["yellow", "black"]" and I'm trying to convert it to C# list
Iv' tried to do the following code
stringList.Trim('[',']').ToList();
But the result is a list if every char
[ "y","e","l","l","o","w"...]
Any ideas of how can I do that?
THX

You can use the new System.Text.Json APIs
JsonSerializer.Parse<List<string>>("[\"yellow\", \"black\"]");
For further information you can read Try the new System.Text.Json APIs.

We use Newtonsoft for all JSON parsing:
string[] arr = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>("[\"yellow\", \"black\"]");

Related

How to deserialise PHP Serialized array in C#

I've got an array string serialised via PHP (Wordpress) similar to the following:
a:2:{i:0;s:12:"Sample array";i:1;a:2:{i:0;s:5:"Apple";i:1;s:6:"Orange";}}
How would I deserialise this string in C#?
If I paste the string into https://www.unserialize.com, it converts the structure fine.
Thanks!
You can use KaitaiStruct library.
Example(source):
// Parse a local file and get structure in memory
var data = PhpSerializedValue.FromFile("path/to/local/file.php_serialized_value");

Parsing incorrect JSON strings

I have JSON on input, which contain arrays like this
[13806008,,[[27017723,,[0.25,-180,145],],[26683222,,[0,-125,106],]],0,"0","0","0","0",null,[[176,"673041"],[168,"2"],[175,"val"],[169,"1"]]]
Chrome Web Inspector parses those double commas like undefined elements, but the Newtonsoft Json library throws an exception with this format.
The only way that I see - insert null between double commas first and parse string then.
Is there faster way to parse such JSON strings?
As Darin Dimitrov says in a comment, this isn't JSON. So it's then up to you to figure out how you want to interpet it. From the example, it looks like a pretty simple 'subset' of JSON, so here's what I'd suggest.
I've written a library called canto34 which lets you write your own interpreters for simple language problems like this, and described a program to recognise nested lists of tokens -- in my case, lisp s-expressions, but these are very similar to nested JavaScript lists, just with different brackets. ;)
Here's the kind of structure you need to parse nested lists;
public class SExpressionParser : ParserBase
{
internal dynamic SExpression()
{
if (LA1.Is(SExpressionLexer.OP))
{
Match(SExpressionLexer.OP);
}
else
{
var atom = Match(SExpressionLexer.ATOM).Content;
return atom;
}
var array = new List<dynamic>();
while (!EOF && !LA1.Is(SExpressionLexer.CL))
{
array.Add(SExpression());
}
Match(SExpressionLexer.CL);
return array;
}
}
Looking closely to my string I realized what that's regular JSON array!
I simply parse my sting as JSON Array!
JArray JsonArray= JArray.Parse(responseString);

Reading more json strings from one file

I've got two different json files and would like to merge them and read json strings from one file.
{"ipAddress":"1.1.1.1","port":80, "protocol":"http"}
{"ipAddress":"1.1.1.1", "domainName":"domain.com"}
I tried something, but it still doesn't work properly. I tried array and also the following structure:
{"jsonString1": {"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
"jsonString2": {"ipAddress":"1.1.1.1", "domainName":"domain.com"}}
Not sure if the structure is correct. I just need to get "jsonString1", "jsonString2" separately so I don't need to use more json files.
Your 1st fragment is non standard (effectively, not JSON).
Your 2nd IS standard, but is an object, not an array.
If you want an array, use an array:
[{"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
{"ipAddress":"1.1.1.1", "domainName":"domain.com"}]
Alternatively, if you want to use your 2nd version (which is an object), you can access the 2 "sub-objects" by keys: myObj.jsonString1, myObj.jsonString2. BTW, A better name would be "Obj1" & "Obj2" since these are not strings, they're actual objects.
Use JSON Array to keep those files merged.For example
Conside,You have an JSON array for URL then and you want to print it in a paragraph then
<p id="url"></p>
declare a variable like this
var URL=[{"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
{"ipAddress":"1.1.1.1", "domainName":"domain.com"}]
you can access these array by using
document.getElementById("url").innerHTML =
URL[0].ipAddress+ " " + URL[0].port+ " " +URL[0].protocol;
You can get the array values by using the index values
Thank you. I have finally used this syntax:
json:
{"jsonString1": {"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
"jsonString2": {"ipAddress":"1.1.1.1", "domainName":"domain.com"}}
read the string using this command:
var jsonObject = JObject.Parse(jsonData);
string value = jsonObject["jsonString1"].ToString();

C# Convert string to array

So I'm working with umbraco and using the tag datatype. I'm trying to take all tags added to a given node and putting them into an array of strings but when I grab the value it always seems to come out like this:
"[\"Tag1\",\"Tag2\"]"
How can I convert this string of an array back into a regular array? All I have gotten so far was a string of individual characters
The array format you have provided as an example looks like part of the JSON object.
You could use JSON.net library to parse array token of the JSON object.
var array = JArray.Parse(tagString).Values<string>();
A complete example is available here.
You could try:
string[] newArray = item.Replace("\"", "").Replace("[", "").Replace("]", "").Split(',');
This would output as Tag1, Tag2 etc...
Hope this helps.
Use this
var tagString = "[\"Tag1\",\"Tag2\",\"Tag3\",\"Tag4\"]";
var tags = tagString.Trim().TrimStart('[').TrimEnd(']').Split(',');

Need help replacing parts of json string with regex

How can I replace the following using Regex.Replace in my c# application?
Replace all of the following:
rendition\":{
with:
rendition\":[{
So i am adding the left square bracket.
and also
Replace:
\"}}
With:
\"}]}
I am using JsonConvert from NewtonSoft to convert XML to json. The rendition element in my xmls may or may not be an array. I am trying to force the converted json to an array
Replace:
(?<=rendition:)\"\{(.*?)\"\}\}
With:
\"[{$1\"}]}
In c#:
string json2 = Regex.Replace(json, "(?<=rendition\\\\\":)\\{(.*?)\\}\\}", "[{$1}]}");
See a live demo of this C# code running on ideone.

Categories

Resources