Below is parsed json data which is of type string.
"data": [
{
"Company": {
"id": "1",
“Value": “20”,
"companyId": "2001”,
}
},
{
"Company": {
"id": "2",
“value”: "20”,
"companyId”: "2002”,
}
},
{
"Company": {
"id": “3”,
“value”: “30”,
"companyId”: "2003”,
}
},
]
var parseData = Newtonsoft.Json.Linq.JObject.Parse (e.ResponseData.ToString ());
Convert json data string store in array, Arraylist of stored Company Value.
this is first time dealing with Json object string.
string json = #"{
'status_code': 200,
'status_text': 'matches found',
'data': [{
'company': {
'id': '1',
'value': '20',
'companyId': '2001',}
},
{
'company': {
'id': '2',
'value': '20',
'companyId': '2002',}
},
{
'company': {
'id': '3',
'value': '30',
'companyId': '2003',}
},]
}";
JObject jObj = JObject.Parse(json);
var ids = jObj["data"].Children()["company"]["companyId"];
var list = new List<string>();
list.AddRange(ids.Select(id => id.Value<string>()));
foreach (var item in list)
Console.WriteLine(item);
// Outputs ->
// 2001
// 2002
// 2003
Edit:
"Everything" from companies as a list:
JObject jObj = JObject.Parse(json);
var jEnum = jObj["data"].Children()["company"];
var list = jEnum.Select(company =>
company.Values().Select(current =>
current.Value<string>()).ToList()).ToList();
Related
I have 3 JSON files that all contain the same data structure, however different data.
The structure for all 3 files is as follows:
{
"TokenId": "0",
"rank": "2804"
},
{
"TokenId": "1",
"rank": "977"
},
{
"TokenId": "2",
"rank": "4085"
}
I am trying to create a new JSON file from these 3 files that has the following structure, and yes, they all have the same tokenID values, but slightly different rank values:
{
"TokenId": "0",
"File1Rank": "2804",
"File2Rank": "2802",
"File3Rank": "2809"
},
{
"TokenId": "1",
"File1Rank": "977",
"File2Rank": "983",
"File3Rank": "999"
},
{
"TokenId": "2",
"File1Rank": "4085",
"File2Rank": "4089",
"File3Rank": "4100"
}
How can I search by the tokenId value in each file to obtain the rank value? I can iterate through each valuea in each file to get both values, but I am struggling to create or update the new JSON correctly. The logic I feel I need is if the TokenId is equal to a certain value, then add the rank key/value, but I have not been able to find the answer on how I can do this.
You can use the newtonsoft json library to parse and update the json files.
If your source file structure is:
{
"Tokens": [
{
"TokenId": "0",
"rank": "2804"
},
{
"TokenId": "1",
"rank": "977"
},
{
"TokenId": "2",
"rank": "4085"
}
]
}
Pseudo code:
using Newtonsoft.Json
using Newtonsoft.Json.Linq
void Main()
{
dynamic objFinal = JObject.Parse("{ 'Tokens':[] }");
JArray finalArray = (JArray)objFinal["Tokens"];
DirectoryInfo dir = new DirectoryInfo(#"D:\Projects\JsonFiles\");
foreach(var file in dir.GetFiles("*.json"))
{
dynamic objJson = JObject.Parse(File.ReadAllText(file.FullName));
JArray tokens = (JArray)objJson["Tokens"];
foreach(JToken token in tokens)
{
JToken searchResult = finalArray.Where(t=> Convert.ToString(t["TokenId"])==Convert.ToString(token["TokenId"])).FirstOrDefault();
if(searchResult==null)
{
//push new tokenid
JArray newFileRanks = new JArray();
newFileRanks.Add(token["rank"]);
dynamic newToken = new JObject();
newToken["TokenId"] = token["TokenId"];
newToken["fileRanks"] = newFileRanks;
finalArray.Add(newToken);
}
else
{
//append to fileRanks
JArray existingFileRanks = (JArray)searchResult["fileRanks"];
dynamic fileRankExists = existingFileRanks.Where(t=> Convert.ToString(t)==Convert.ToString(token["rank"])).FirstOrDefault();
if(fileRankExists==null)
{
existingFileRanks.Add(token["rank"]);
}
}
}
}
Console.Write(JsonConvert.SerializeObject(objFinal));
}
Final output:
{
"Tokens": [
{
"TokenId": "0",
"fileRanks": [ "2804", "2801" ]
},
{
"TokenId": "1",
"fileRanks": [ "977", "972" ]
},
{
"TokenId": "2",
"fileRanks": [ "4085", "4083" ]
}
]
}
I got a json result as shown in image 1 but I need an output shown in image 2.
I took the following classes
public class NameDTO
{
public string Name;
}
public class ValDTO
{
public string Val;
}
I got the list to the above classes as shown in figure 3 and 4 and combining them and converting to json.
var combined1 = _nameDetials1.Zip(_valDetials1, (name1, val1) => new { name1.Name, val1.Val }) .ToDictionary(k => k.Name, k => k.Val);
var jsonSerialiser1 = new JavaScriptSerializer();
var json1 = jsonSerialiser1.Serialize(combined1);
How can I do the grouping so that I can get he correct output as shown in image2
Thanks.
If it is possible you can use Json.NET.
Here an example to solve your problem.
const string JSON = #"{
""message-Code-1"": ""000"",
""msg-Number-Pos1-1"": ""0000"",
""msg-Number-Pos2-1"": ""1"",
""msg-Number-Pos3-1"": ""1"",
""message-Code-2"": ""1"",
""msg-Number-Pos1-2"": ""0001"",
""msg-Number-Pos2-2"": ""2"",
""msg-Number-Pos3-2"": ""1"",
""message-Code-3"": ""0002"",
""msg-Number-Pos1-3"": ""3"",
""msg-Number-Pos2-3"": ""1"",
""msg-Number-Pos3-3"": ""1"",
""message-Code-4"": ""0003"",
""msg-Number-Pos1-4"": ""3"",
""msg-Number-Pos2-4"": ""1"",
""msg-Number-Pos3-4"": ""1""
}";
JObject loMessages = JObject.Parse(JSON);
JArray loMessageArray = new JArray();
JObject loAddMessage;
foreach (var loMessageGroup in loMessages.Properties().GroupBy(item => Regex.Match(item.Name,#".*-(?<pos>\d+)").Groups["pos"].Value))
{
loAddMessage = new JObject();
foreach (var loMessage in loMessageGroup)
loAddMessage[loMessage.Name] = loMessage.Value.ToString();
loMessageArray.Add(loAddMessage);
}
Console.WriteLine(loMessageArray.ToString());
The Json Ouput is like this:
[
{
"message-Code-1": "000",
"msg-Number-Pos1-1": "0000",
"msg-Number-Pos2-1": "1",
"msg-Number-Pos3-1": "1"
},
{
"message-Code-2": "1",
"msg-Number-Pos1-2": "0001",
"msg-Number-Pos2-2": "2",
"msg-Number-Pos3-2": "1"
},
{
"message-Code-3": "0002",
"msg-Number-Pos1-3": "3",
"msg-Number-Pos2-3": "1",
"msg-Number-Pos3-3": "1"
},
{
"message-Code-4": "0003",
"msg-Number-Pos1-4": "3",
"msg-Number-Pos2-4": "1",
"msg-Number-Pos3-4": "1"
}
]
I have JSON Like below
{
"_id": "0FEB6D4B-8DA5-4143-B926-11A7AE4F3B12",
"device": {
"name": "test",
"family": "test"
},
"channels": [
{
"mcl": 33,
"vtype": "FLOAT",
"category": " Current"
},
{
"tag": "OperationMode",
"vtype": "BYTE",
"enums": [
{
"0": "Off"
},
{
"1": "On"
},
{
"2": "ByPass"
}
]
}
]
}
I am using Json.net to deserialize the JSON to C# object. I am not able to manage to convert the enum list. I validated if this is valid JSON. I tried with custom converter & string converter but reader value is null. Any quick help appreciated.
JObject jR = JObject.Parse(YourJsonString);
JArray oR = (JArray)jR["channels"];
JArray jA = (JArray)oR[1]["enums"];
foreach (var item in jA)
{
Dictionary<string,string> enums = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(item.ToString());
foreach (var en in enums)
{
Console.WriteLine(en.Value);
}
}
Fiddler: https://dotnetfiddle.net/ziSep1
I am usin NewtonSoft JSON.Net and I have a JObject that I need to add and remove items to and form it dynamicly from my code.
If this is my json:
{
"IgnoredInterests": [
{
"Id": 1,
"Name": "test"
},
{
"Id": 2,
"Name": "test"
}
]
}
I need to be able to add more items or even remove items from it via code.
How can I add this to the JObject:
{
"Id": 3,
"Name": "test"
}
And even remove:
{
"Id": 2,
"Name": "test"
}
I appreciate your help...
string json = #"{
'IgnoredInterests': [
{
'Id': 1,
'Name': 'test'
},
{
'Id': 2,
'Name': 'test'
}
]
}";
JObject obj = JObject.Parse(json);
string json_add = #"{
'Id': 3,
'Name': 'test'
}";
JArray array = obj.GetValue("IgnoredInterests") as JArray;
JObject obj_add = JObject.Parse(json_add);
array.Add(obj_add);
foreach (JObject item in array.Children())
{
if (item.GetValue("Id").ToString() == "2")
{
array.Remove(item);
break;
}
}
I am executing a linq query which gets me all the records from a table:
var data = _context.People.ToList(); //_context is my DataContext.
The above returns the the value:
{
"name": "john",
"age": "30"
},
{
"name": "jane",
"age": "31"
}
but according to jsonlint, this is invalid and I need to have it be returned as:
[{
"name": "john",
"age": "30"
},
{
"name": "jane",
"age": "31"
}]
How can I do this?
viewData.xldata = [];
$.each(data, function(i, row) {
var strRow = JSON.stringify(row);
viewData.xldata.push(strRow);});
Deserialize using `JavaScriptSerializer:
var people = jss.Deserialize<List<People>>(args["xldata"]);
Try this:
List<People> data= _context.People.ToList();
System.Web.Script.Serialization.JavaScriptSerializer objSerializer = default(System.Web.Script.Serialization.JavaScriptSerializer);
objSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return objSerializer.Serialize(data);