How to split an array list?
Here is the array of the list:
{"things":{"1":"1_4","3":"3_13","4":"4_18","5":"5_25","6":"6_28","7":"7_32"}}
here is the code:
var t = things;
string aa = t[0].ToString();
How to split the above array, separator and _. from the above array, I only want 1_4,3_13 ... this column and store in two different var.
when i use
string[] ss = aa.Split(new char[] { ',', '|', }, System.StringSplitOptions.RemoveEmptyEntries);
the problem is that in the first list {"things": {"1": "1_4". comes
so how to remove {"things" ??
source to share
You don't have to parse the JSON yourself. Don't reinvent the wheel.
You must define a class
public class MyClass
{
[JsonProperty("things")]
public Dictionary<int, string> Things { get; set; }
}
Then deserialize your string into an instance MyClass
var rawData = "{\"things\":{\"1\":\"1_4\",\"3\":\"3_13\",\"4\":\"4_18\",\"5\":\"5_25\",\"6\":\"6_28\",\"7\":\"7_32\"}}";
var data = JsonConvert.DeserializeObject<MyClass>(rawData);
Then you can use data
Console.WriteLine(data.Things[1]);
You have to add the Newtonsoft.Json Nuget package to your project and add the namespace using Newtonsoft.Json
to your code file.
source to share
Instead of string manipulation, you should use a JSON library like Json.Net . Just because you are working with a JSON string, it will be easier to work with this information if you deserialize it to the correct object
or JObject
.
Example with JObject
:
string json = @"{""things"":{""1"":""1_4"",""3"":""3_13"",""4"":""4_18"",""5"":""5_25"",""6"":""6_28"",""7"":""7_32""}}";
var jObj = Newtonsoft.Json.Linq.JObject.Parse(json);
var prop1 = jObj.GetValue("things").GetPropertyValue("1").ConvertTo<string>();
var prop4 = jObj.GetValue("things").GetPropertyValue("4").ConvertTo<string>();
Note. You can create classes that will represent your JSON structure if you want to have a strongly typed object structure.
source to share
First you need to split by {
and then discard the first, and after that you are left with:
"1": "1_4", "3": "3_13", "4": "4_18", "5": "5_25", "6": "6_28", "7": "7_32"}}
Now you divide ,
and get
"1": "1_4"
"3": "3_13", etc.
Then you break each one into :
and take the second one.
Remember only that the last "7_32"}}
one to be removed with}}
Like this:
var elems = aa.Split(new[] { '{' })[1].Split(new[] { ',' });
var res = elems.Select(obj => obj.Trim("}".ToCharArray()).Split(new[] { ':' }));
Hope this is what you want :)
source to share