Arnab Arnab - 2 years ago 198
JSON Question

Replace json array elements with elements of another array c#

I have two json strings..

string days = "['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']";
string data= "[[0,0,0],[2,1,0],[0,2,0],[3,3,0],[0,6,0],[0,7,0],[5,8,0],[0,9,1],[6,10,3],[0,11,5],[0,12,4],[4,13,7],[0,14,1]]";

I would like to convert the json data such that..

for all array such as [0,0,0]

a)if the last value is 0 remove this array from data

b) replace the first value with the first value in days array
eg ..[3,13,7] becomes ["Wednesday",13,7]

I started with this..

JArray daysarr = JArray.Parse(days);
JArray myarr = JArray.Parse(data);
foreach (var myobj in myarr)
// what do I do here????

Any help is sincerely appreciated..


Answer Source

What about this solution:

var js = new JavaScriptSerializer();
string days = "['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']";
string data = "[[0,0,0],[2,1,0],[0,2,0],[3,3,0],[0,6,0],[0,7,0],[5,8,0],[0,9,1],[6,10,3],[0,11,5],[0,12,4],[4,13,7],[0,14,1]]";

var Days = js.Deserialize<List<string>>(days);
var Data = js.Deserialize<List<List<int>>>(data);

var answer = js.Serialize(Data.Where(x => x.Last() != 0).ToList().Select(x => {
    var list = new List<object> { Days[x.First()] };
    list.AddRange(x.Skip(1).Select(y => (object)y).ToList());
    return list;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download