How to convert object which is like to json object to c#? - c#

I have an object returned from API. It is very like to json but it is not. I printed it in visual studio immediate window. Something like.
[0]: {{
"projectId": 111,
"userId": 11,
"name": "Bill, Gates",
"value": "11"
}}
[1]: {{
"projectId": 222,
"userId": 22,
"name": "Cill, Gates",
"value": "22"
}}
// .....many
It is not json type. So I use cast
IEnumerable<MyClass> list = obj.Cast<object>();
public class MyClass
{
public int projectId {get; set;}
public int userId {get; set;}
public string name {get; set;}
public string value {get; set;}
}
However when I loop through the list
foreach(var item in list)
{
var temp = item.value;
}
I can't get item or temp. Hover it or print it in the immediate window; it shows
NullReferenceException
I assume that I have to convert the object to real json type rather then using cast<object>.
So what is the best way?

You can try something like this:
json = Regex.Replace(json, #"\[[0-9]+\]:", ""); // remove [0]:
json = json.Replace("{{", "{");
json = json.Replace("}}", "},");
json = $"[{json}]";
var obj = JsonConvert.DeserializeObject(json);
might need more work if you have more nested objects

Okay, so I was experimenting with your string and trying to use Regular Expressions and I have found a way to parse your string into your corresponding MyClass structure. I hope this helps you out:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string str = #"[0]: {{
'projectId': 111,
'userId': 11,
'name': 'Bill, Gates',
'value': '11'
}}
[1]: {{
'projectId': 222,
'userId': 22,
'name': 'Cill, Gates',
'value': '22'
}}";
try
{
showMatch(str, #"('(.*)':(.*)[',])");
}
catch(Exception ex)
{
Console.WriteLine("Exception occured: "+ex.Message);
}
}
static private void showMatch(string text, string expr)
{
//Declare what is required! Phew
List<MyClass> output = new List<MyClass>();
int projectId=0;
int userId=0;
string name=string.Empty;
string value=string.Empty;
var regEx = new Regex(#"[^0-9a-zA-Z]+");
//Start the matching process
MatchCollection mc = Regex.Matches(text, expr);
bool check;
foreach (Match m in mc)
{
check = false;
string[] parsed = m.ToString().Split(':');
var stripped = regEx.Replace(parsed[1], "");
if (parsed[0] == "'projectId'")
{
projectId = Convert.ToInt32(stripped);
}
if (parsed[0] == "'userId'")
{
userId = Convert.ToInt32(stripped);
}
if (parsed[0] == "'name'")
{
name = stripped;
}
if (parsed[0] == "'value'")
{
value = stripped;
check = true;
}
//Add to list
if(check==true)
{
output.Add(new MyClass { projectId = projectId, userId = userId, name = name, value = value });
}
}
output.Dump();
}
}
public class MyClass
{
public int projectId { get; set; }
public int userId { get; set; }
public string name { get; set; }
public string value { get; set; }
}
Output:
[
{
name : BillGates
projectId : 111
userId : 11
value : 11
},
{
name : CillGates
projectId : 222
userId : 22
value : 22
}
]
Working DEMO: https://dotnetfiddle.net/TCXVde

Related

C# merge 2 almost identical JSON objects

A while ago I made a function that merged JSON together.
I had a table looking like this, which in this example has been made by left joining the table 'friends' on the table 'persons':
Id
Name
FriendName
FriendAge
1
Danny
Jason
19
1
Danny
Cesie
18
2
Jason
Danny
19
And it would result in a json object looking like this:
[
{
"Id": 1,
"Name": "Danny",
"Friends": [
{
"Name": "Jason",
"Age": 19
},
{
"Name": "Cesie",
"Age": 18
}
]
},
{
"Id": 2,
"Name": "Jason",
"Friends": [
{
"Name": "Danny",
"Age": 19
}
]
}
]
I did this by using the following C# code:
using System;
using System.Data;
using Newtonsoft.Json;
namespace JsonTest
{
class Program
{
private class Result
{
public int Id { get; set; }
public string Name { get; set; }
public Friend[] Friends { get; set; }
}
private class Friend
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main(string[] args)
{
string json = "[{\"Id\":1,\"Name\":\"Danny\",\"FriendName\":\"Jason\",\"FriendAge\":19},{\"Id\":1,\"Name\":\"Danny\",\"FriendName\":\"Cesie\",\"FriendAge\":18},{\"Id\":2,\"Name\":\"Jason\",\"FriendName\":\"Danny\",\"FriendAge\":19}]";
// Original table from example
DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);
// Get distinct values from DataTable
DataView dv = new DataView(dt);
DataTable distinct_values = dv.ToTable(true, "Id");
Result[] result = new Result[distinct_values.Rows.Count];
int i = 0;
foreach (DataRow row in distinct_values.Rows)
{
// Filter the original table on one Id from the distinct values
dv.RowFilter = $"Id = {row["Id"]}";
DataTable temp_dt = dv.ToTable();
Result temp = new Result();
// Copy general data over to the temp
temp.Id = Convert.ToInt32(temp_dt.Rows[0]["Id"].ToString());
temp.Name = temp_dt.Rows[0]["Name"].ToString();
Friend[] rows = new Friend[temp_dt.Rows.Count];
// loop over all the rows and copy the array data over
int j = 0;
foreach (DataRow temprow in temp_dt.Rows)
{
rows[j] = new Friend();
rows[j].Name = temprow["FriendName"].ToString();
rows[j].Age = Convert.ToInt32(temprow["FriendAge"].ToString());
j++;
}
// Assign everything to where it it supposed to be
temp.Friends = rows;
result[i] = temp;
i++;
}
Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
Console.ReadLine();
}
}
}
It works really well. But my question, is there another, cleaner or faster, way to do this entire operation? If so, where can I find this? Thanks in advance.
I would create a model to carry your data easier than using DataTable
public class RequestModel{
public int Id { get; set; }
public string Name { get; set; }
public string FriendName { get; set; }
public int FriendAge { get; set; }
}
Then you can try to use lambda to make it, using GroupBy method get grouping by Id, Name.
string json = "[{\"Id\":1,\"Name\":\"Danny\",\"FriendName\":\"Jason\",\"FriendAge\":19},{\"Id\":1,\"Name\":\"Danny\",\"FriendName\":\"Cesie\",\"FriendAge\":18},{\"Id\":2,\"Name\":\"Jason\",\"FriendName\":\"Danny\",\"FriendAge\":19}]";
var req = JsonConvert.DeserializeObject<IEnumerable<RequestModel>>(json);
var res= req.GroupBy(x=> new {x.Id,x.Name})
.Select(x=> new Result{
Name =x.Key.Name,
Id = x.Key.Id,
Friends = x.Select(z=> new Friend(){
Name = z.FriendName,
Age = z.FriendAge
}).ToArray()
});
var jsonResult = JsonConvert.SerializeObject(res);

Parsing json file in c# to get into all sections and properties

==========Update
So in trying to phrase the issue properly, I have misled the responders in not giving me the answer I need. Apologies, let me try to clarify.
I need to be able to cycle through a json file that is not as structured as I indicated in the OP, it is much more random. The OP file did not convey that very well.
Let me try to describe what is closer to the file I'll be getting. The first two levels will be fixed, I'll call them LevelA and LevelB. But the properties in LevelB can be any pair of random data. This is a better json file example:
{
"LevelA": {
"LevelB": [
{
"EmpName": "John",
"EmpGender": "Male",
"Age": "25"
},
{
"FavoriteFood": "Beer",
"BaseballTeam": "Kansas City Royals"
},
{
"Red": "10",
"Blue": "40",
"White: "True"
}
]
}
}
Say I need to write out the following to console:
A LevelB entry has these properties:
Property: EmpName, Value: John
Property: EmpGender, Value: Male
Property: Age, Value: 25
A LevelB entry has these properties:
Property: FavoriteFood, Value: Beer
Property: BaseballTeam, Value: Kansas City Royals
A LevelB entry has these properties:
Property: Red, Value: 10
Property: Blue, Value: 40
Property: White, Value: True
It may not make sense but, I need to find a way to do that, I need that knowledge. I appreciate the answers about using a model, but I don't see a way to use a model without complicating what I think should be a simple task. Although not simple enough for me to figure out apparently. :)
==========
C#, VS 2019, a .NET framework console test app. I'm looking to do something simple but I can't find the right syntax.
I have a json file with the following structure. I want to loop through each Employee below and get at its properties (name, gender, etc...):
{
"Company": {
"Employees": [
{
"EmpName": "John",
"EmpGender": "Male",
"Age": "25"
},
{
"EmpName": "Mary",
"EmpGender": "Female"
},
{
"EmpName": "Bill",
"Age": "30"
}
]
}
}
First question is which package will do the job? I've installed Microsoft.Extensions.Configuration.Json and System.Configuration.ConfigurationManager but am having difficulties getting the syntax correct. Are these the right packages to use? I decided to use those because I thought I could load the file via ConfigurationBuilder and that the GetSection and/or GetChildren methods would help me. I can load the file but I can't figure out how to use those methods to give me what I want.
Second I don't want to build a model for this, I just want at the data. If I can get each employee into a dictionary, I can analyze that, and that would get me going. Thanks for any advice.
You can use the built-in JSON library in the .net core
using System.Text.Json;
add the following model definition
public class Rootobject
{
public Company Company { get; set; }
}
public class Company
{
public Employee[] Employees { get; set; }
}
public class Employee
{
public string EmpName { get; set; }
public string EmpGender { get; set; }
public string Age { get; set; }
}
deserialize your object like the following
string jsonData = File.ReadAllText("data.json");
Rootobject ob = JsonSerializer.Deserialize<Rootobject>(jsonData);
now you have ob in you c# represent your JSON as C# object
I don't want to build a model for this
if you use Visual Studio you can auto generate your model classes required for your JSON as described here the above models are auto generated by Visual Studio
If you don't want to create a model,and get a List<Dictionary<string,string>>,you can use custom model binding,here is a demo:
CustomBinder:
public class CustomBinder:IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var model = new List<Dictionary<string, string>>();
using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body))
{
var body = reader.ReadToEndAsync();
var mydata = JsonConvert.DeserializeObject<JObject>(body.Result);
var s = mydata["Company"]["Employees"].ToString();
var list=JsonConvert.DeserializeObject<List<JObject>>(s);
foreach (var jobj in list) {
Dictionary<string, string> d = new Dictionary<string, string>();
foreach (var x in jobj)
{
string name = x.Key;
string value = x.Value.ToString();
d.Add(x.Key, x.Value.ToString());
}
model.Add(d);
}
}
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}
}
Action:
public void TestJson1([ModelBinder(BinderType = typeof(CustomBinder))] List<Dictionary<string, string>> jsondata)
{
}
result:
Why is it a requirement not to build models? In my opinoin that is the easiest way and if you need to expand due to JSON changes, you can easily adapt it in the code. I paste a sample code here what is using System.Text.Json namespace (no other packages are also required due to it is built-in).
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace jsontest
{
class Program
{
static void Main(string[] args)
{
string input = "{ \"Company\": { \"Employees\": [{ \"EmpName\": \"John\", \"EmpGender\": \"Male\", \"Age\": \"25\" }, { \"EmpName\": \"Mary\", \"EmpGender\": \"Female\" }, { \"EmpName\": \"Bill\", \"Age\": \"30\" }]}}";
var processedInput = JsonSerializer.Deserialize<Company>(input);
foreach (var item in processedInput.Peoples.PeopleList)
{
Console.WriteLine($"{item.Name} - {item.Gender} - {item.Age}");
}
}
}
public class Employee
{
[JsonPropertyName("EmpName")]
public string Name { get; set; }
[JsonPropertyName("EmpGender")]
public string Gender { get; set; }
[JsonPropertyName("Age")]
public string Age { get; set; }
}
public class Employees
{
[JsonPropertyName("Employees")]
public List<Employee> PeopleList { get; set; }
}
public class Company
{
[JsonPropertyName("Company")]
public Employees Peoples { get; set; }
}
}
Update after your update:
Strange why you store data in JSON on this way. I wrote a quick code, it is using regex and some built-in function to parse the text. At the end result is similar what you would prefer. Code is a bit long, but only because I put some comment to make understanding easier.
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace jsontest
{
class Program
{
static void Main(string[] args)
{
List<List<ListItem>> result = new List<List<ListItem>>();
string input = "{ \"Company\": { \"Employees\": [{ \"EmpName\": \"John\", \"EmpGender\": \"Male\", \"Age\": \"25\" }, { \"EmpName\": \"Mary\", \"EmpGender\": \"Female\" }, { \"EmpName\": \"Bill\", \"Age\": \"30\" }]}}";
// Remove new lines, so input will become one single line
input = input.Replace(Environment.NewLine, " ");
// 1. group is the group name (in this case Employees)
// 2. group is the content after group name
string pattern1 = #"[{].+[{](.+)[\[](.+)[\]]";
foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(input, pattern1))
{
// groupName -> "Employees":
string groupName = m.Groups[1].Value;
// groupName -> Employees
groupName = groupName.Substring(0, groupName.LastIndexOf("\""));
groupName = groupName.Substring(groupName.IndexOf("\"") + 1);
// contentList -> { "EmpName": "John", "EmpGender": "Male", "Age": "25" }, { "EmpName": "Mary", "EmpGender": "Female" }, { "EmpName": "Bill", "Age": "30" }
string contentList = m.Groups[2].Value;
// Split the line onto more lines where "}," characters
// { "EmpName": "John", "EmpGender": "Male", "Age": "25"
// { "EmpName": "Mary", "EmpGender": "Female"
// { "EmpName": "Bill", "Age": "30" }
string[] contentItems = contentList.Split("},");
foreach (var item in contentItems)
{
// Check every group and store them in separate list
result.Add(new List<ListItem>());
string[] keys = item.Split(",");
foreach (var key in keys)
{
// Check every Key-Value pair and store their value in the current list
string pattern2 = "[\"](.+)[:].[\"](.+)[\"]";
foreach (System.Text.RegularExpressions.Match m2 in System.Text.RegularExpressions.Regex.Matches(key, pattern2))
{
result[result.Count - 1].Add(new ListItem() { Property = groupName, Key = m2.Groups[1].Value.Substring(0, m2.Groups[1].Value.Length - 1), Value = m2.Groups[2].Value });
}
}
}
}
for (int i = 0; i < result.Count; i++)
{
for (int j = 0; j < result[i].Count; j++)
{
if (j == 0)
Console.WriteLine($"A {result[i][j].Property} entry has these properties:");
Console.WriteLine($"Proprty: {result[i][j].Key}, Value: {result[i][j].Value}");
}
}
}
}
class ListItem
{
public string Property { get; set; }
public string Key { get; set; }
public string Value { get; set; }
}
}
Output of this code is:
A Employees entry has these properties:
Proprty: EmpName, Value: John
Proprty: EmpGender, Value: Male
Proprty: Age, Value: 25
A Employees entry has these properties:
Proprty: EmpName, Value: Mary
Proprty: EmpGender, Value: Female
A Employees entry has these properties:
Proprty: EmpName, Value: Bill
Proprty: Age, Value: 30

How can i search a json response to see if a value exists using linq?

I have the following json response
{
"Id": "1234",
"Name": "Test",
"Orders": [
{
"OrderId": "87654",
"OrderDetails": {
"OrdId": "1234",
"Name": "Desk"
}
},
{
"OrderId": "54213",
"OrderDetails": {
"OrdId": "4321",
"Name": "Table"
}
}
]
}
I want to search the list of orders to see if there is an OrderId of 87654.
I can do with an array , but how can I do it with Linq ?
You can deserialize the json string to a JObject using Newtonsoft.Json and then loop through the orders to get the OrderIDs.
var obj = JObject.Parse(json);
foreach(var order in obj["Orders"])
{
Console.WriteLine(order["OrderId"]);
}
or you can use the Where clause.
var myOrder = obj["Orders"].Where(x => x["OrderId"].ToString().Equals("87654")).FirstOrDefault();
Then you can print any property of that order,
Console.WriteLine(myOrder["OrderDetails"]["Name"].ToString());
// Prints: Desk
Alternatively, you can: also use classes to deserialize the json you have and query the orders.
public class OrderDetails
{
public string OrdId { get; set; }
public string Name { get; set; }
}
public class Order
{
public string OrderId { get; set; }
public OrderDetails OrderDetails { get; set; }
}
public class RootObject
{
public string Id { get; set; }
public string Name { get; set; }
public List<Order> Orders { get; set; }
}
public static void Main(string[] args)
{
string json = File.ReadAllText(#"C:\temp\json.txt");
var obj = JsonConvert.DeserializeObject<RootObject>(json);
var myOrder = obj.Orders.FirstOrDefault(x => x.OrderId.Equals("87654"));
if (myOrder != null)
{
Console.WriteLine(myOrder.OrderDetails.Name);
}
}
Demo on dotnet fiddle
You can use Newtonsoft to achieve it
var jsonData = "{ 'Id': '1234', 'Name': 'Test', 'Orders': [ {'OrderId': '87654', 'OrderDetails': { 'OrdId': '1234', 'Name': 'Desk' } }, { 'OrderId': '54213', 'OrderDetails': { 'OrdId': '4321','Name': 'Table' }}]}";
var desirializedData = JsonConvert.DeserializeObject<MyObject>(jsonData);
var result = desirializedData.Orders.Where(p => p.OrderId == 87654);
foreach(var master in result)
{
Console.WriteLine(master.OrderId + " " + master.OrderDetails.Name);
}

JSON string to model / HashMap/ Dictionary in C#

I have JSON:
{
"One": [
{
"ID": 1,
"name": "s"
},
{
"categoryID": 2,
"name": "c"
}
],
"Two": [
{
"ID": 3,
"name": "l"
}
],
"Three": [
{
"ID": 8,
"name": "s&P"
},
{
"ID": 52,
"name": "BB"
}
]
}
I want to:
Take this JSON to any object(like JObject)
Filter the JSON on different conditions(like name start with s, etc
Return this JSON to client
Things I have tried:
1. Creating models:
class Model
{
public int Id;
public string name;
}
class MainModel
{
public string mainName;
public List<Model> categories;
}
And use these model to:
List<MainModel> m = json_serializer.DeserializeObject(jsonString);
I tried to Dictionary also but getting unable to cast exception.
any help would be appreciated.
The following will allow you to deserialize your JSON to a Dictionary and filter on it. This uses Newtonsoft.Json Nuget package, but that's fairly common. Code posted below. Working example found here .Net Fiddle.
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var json = "{\"One\": [{ \"ID\": 1, \"name\": \"s\"},{ \"categoryID\": 2, \"name\": \"c\"}],\"Two\": [{ \"ID\": 3, \"name\": \"l\"}],\"Three\": [{ \"ID\": 8, \"name\": \"s&P\"},{ \"ID\": 52, \"name\": \"BB\"}]}";
var deserialized = JsonConvert.DeserializeObject<Dictionary<string, List<Model>>>(json);
Console.WriteLine(deserialized["One"][0].name);
Console.WriteLine("Filter to starts with s");
var filtered = deserialized.SelectMany(item => item.Value).Where(innerItem => innerItem.name.StartsWith("s"));
foreach(var item in filtered){
Console.WriteLine(item.name);
}
}
public class Model{
public int ID {get;set;}
public string name {get;set;}
public int categoryID {get;set;}
}
}
I have written this code assuming that:
One, Two and Three are a MainCategory -which is seralized as JProperty from a KeyValuePair<string name, List<SubCategory> values>. Long type name, eh? Add the following if you want to use the result dictionary often:
using MainCategories = System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<JsonDeSerializtionTest.SubCategory>>;
categoryID and ID are properties that descibe an Id and can not co-exist on the same SubCategory but do change the type of SubCategory.
1. Create the SubCategory class:
public class SubCategory
{
[JsonIgnore]
public DataTypes DataType { get; set; }
[JsonIgnore]
public string Parent { get; set; }
[JsonProperty("ID")]
public int Id { get; set; }
[JsonProperty("categoryID")]
public int CategoryId => Id;
[JsonProperty("name")]
public string Name { get; set; }
public bool ShouldSerializeId()
{
return DataType == DataTypes.Id;
}
public bool ShouldSerializeCategoryId()
{
return DataType == DataTypes.CategoryId;
}
}
2. Create the Deserialize(string json) function:
private static MainCategories Deserialize(string json)
{
Dictionary<string, List < SubCategory >> jsonBody = new Dictionary<string, List<SubCategory>>();
JObject jObject = JObject.Parse(json);
// the outer object {one...two..}
foreach (KeyValuePair<string, JToken> jMainCategory in jObject)
{
// jMainCategory => "one": [{...}, {...}]
string key = jMainCategory.Key;
List<SubCategory> values = new List<SubCategory>();
foreach (JObject jSubCategory in jMainCategory.Value)
{
//jsubCategory => {"name" : ..., "ID": ... }
SubCategory subCategory = new SubCategory();
JToken idProperty;
if (jSubCategory.TryGetValue("ID", out idProperty))
{
subCategory.DataType = DataTypes.Id;
subCategory.Id = idProperty.Value<int>();
}
else
{
subCategory.DataType = DataTypes.CategoryId;
subCategory.Id = jSubCategory["categoryID"].Value<int>();
}
subCategory.Name = jSubCategory["name"].Value<string>();
subCategory.Parent = key;
// subCategory.AnotherProperty = jSubCategory["anotherproperty"].Value<type>();
values.Add(subCategory);
}
jsonBody.Add(key, values);
}
return jsonBody;
}
3. Use the function to get a Dictionary<string, List<SubCategory>> which you can use for sorting and filtering. Example:
public static MainCategories WhereNameStartsWith(this MainCategories jsonBody, string str)
{
MainCategories result = new MainCategories();
//if you want to keep the result json structure `as is` return a MainCategories object
foreach (var subCategory in jsonBody.SelectMany(mainCategory => mainCategory.Value).Where(subCategory => subCategory.Name.StartsWith(str)))
{
if(result.ContainsKey(subCategory.Parent))
result[subCategory.Parent].Add(subCategory);
else
result.Add(subCategory.Parent, new List<SubCategory> {subCategory});
}
// if you just want the subcategories matching the condition create a WhereListNameStartsWith method
// where `result` is a list of subcategories matching the condition
return result;
}
Upside:
No playing around with NewtonSoft JsonConverter or ContractResolvers.
The ability to use LINQ to easily sort Name AND CategoryId/Id which have the same value but make a different SubCategory.DataType:
foreach (var subCategory in jsonBody.SelectMany(mainCategory => mainCategory.Value).Where(subCategory => subCategory.DataType == DataTypes.CategoryId))
You can easily serialize the JSON back to string representation. Example:
string jsonIn ="{\"One\":[{\"ID\":1,\"name\":\"s\"}," +
"{\"categoryID\":2,\"name\":\"c\"}]," +
"\"Two\":[{\"ID\":3,\"name\":\"l\"}]," +
"\"Three\":[{\"ID\":8,\"name\":\"s&P\"}," +
"{\"ID\":52,\"name\":\"BB\"}]}";
MainCategories desrializedJson = Deserialize(jsonIn);
MainCategories filtered = desrializedJson.WhereNameStartsWith("s");
string jsonOut = JsonConvert.SerializeObject(desrializedJson, Formatting.None);
Debug.Assert(jsonOut == jsonIn); //true
Removes the need for null checking when accessing Id/CategoryId.
My favorite: using C# syntax for property names.
Downside:
I don't know. This is a paste and forget soltuion :P
Probably a harder time when changing your JSON structure (although I might argue it would make things much easier for you)
Notes:
Parent is optional and is used to make things easier when using LINQ
DataTypes is an enum which is used to determine wether ID or categoryID was found if you want such information and also to serialize the proper property (identical two way convertion)
public enum DataTypes
{
Id,
CategoryId
};

Read JSON string as key value

I have following json:
{
"serverTime": "2013-08-12 02:45:55,558",
"data": [
{
"key1": 1,
"key2": {},
"key3": {
"key4": [
""
],
"key5": "test2"
},
"key7": 0
},
{
"key8": 1,
"key9": {},
"key10": {
"key4": [
""
],
"key9": "test2"
},
"key11": 0
}
]
}
I want to get values as key value pair. Something like:
jsonObject[data][0]
should give first item of the data array.
I am using JSONFx.net. But it gives strongly typed objects. I do not want that.
Is there any way to parse JSON as key value as I mentioned earlier?
Thanks
Try this:
using System;
using System.IO;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText("input.txt");
var a = new { serverTime = "", data = new object[] { } };
var c = new JsonSerializer();
dynamic jsonObject = c.Deserialize(new StringReader(json), a.GetType());
Console.WriteLine(jsonObject.data[0]);
}
}
If you're not averse to using Json.NET, you can do this:
var jsonString = #"
{
""serverTime"": ""2013-08-12 02:45:55,558"",
""data"": [
{
""key1"": 1,
""key2"": {},
""key3"": {
""key4"": [
""""
],
""key5"": ""test2""
},
""key7"": 0
},
{
""key8"": 1,
""key9"": {},
""key10"": {
""key4"": [
""""
],
""key9"": ""test2""
},
""key11"": 0
}
]
}";
var jsonResult = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
var firstItem = jsonResult["data"][0];
firstItem would be an array of the first item in the data array:
Hope this helps.
First create classes to parse string
public class Key2
{
}
public class Key3
{
public List<string> key4 { get; set; }
public string key5 { get; set; }
}
public class Key9
{
}
public class Key10
{
public List<string> key4 { get; set; }
public string key9 { get; set; }
}
public class Datum
{
public int key1 { get; set; }
public Key2 key2 { get; set; }
public Key3 key3 { get; set; }
public int key7 { get; set; }
public int? key8 { get; set; }
public Key9 key9 { get; set; }
public Key10 key10 { get; set; }
public int? key11 { get; set; }
}
public class RootObject
{
public string serverTime { get; set; }
public List<Datum> data { get; set; }
}
add reference of Newtonsoft.Json.dll
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonData);
then you can access values .
If you want to do this without third party libraries then do:
I would use the following code:
var deserializer = new JavaScriptSerializer();
var someObject = deserializer.DeserializeObject(json);
string serverTime = someObject["serverTime"].ToString();
Dictionary<string, int> data = someObject["data"] as Dictionary<string, int>;
Give it a go.
Edit: You may need to change the last line to:
Dictionary<string, int?> data = someObject["data"] as Dictionary<string, int?>;

Categories

Resources