I receive a JSON string from a external system and I want to turn in to C# objects. The problem is that the "CAR" objects are unique in the string and I do not know how many there is (0 to many).
Now, It doesn't make sense to hardcode classes for each "CAR" like class: CAR1, class: CAR2 and so on. I tried to create a general CAR class and was thinking I could loop throu the JSON and create CAR objects.
The problem is that I cant't identify and find each CAR dynamically.I find the attributes and values for "CAR1" by hardcode "CAR1".
I would like to find a solution like:
foreach(item.key where key starts with "CAR")
Tried the following:
var expConverter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(jsondata, expConverter);
dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsondata);
foreach (var itm in obj)
{
string s = itm.Key;
if(s.StartsWith("CAR"))
{
CarObj = new Car();
CarObj.HP = json.CAR1[0].HORSEPOWER[0];
CarObj.COLOR = json.CAR1[0].COLOR[0];
// Would like to use something like
// CarObj.HP = json.**item.key**[0].HORSEPOWER[0];
}
}
{
"CAR1": [{
"HORSEPOWER": ["180", "int", "Hp"],
"COLOR": ["GREEN", "string", "COLOR"]
}],
"CAR2": [{
"HORSEPOWER": ["200", "int", "Hp"],
"COLOR": ["BlUE", "string", "COLOR"]
}]
}
You're not forced to use dynamic right away. First use the strongly-typed APIs to find the right portion of the JSON, then switch to dynamic:
var obj = JObject.Parse(json);
foreach (var element in obj)
{
if (element.Key.StartsWith("CAR"))
{
dynamic value = element.Value;
var carObj = new Car();
carObj.HP = value[0].HORSEPOWER[0];
}
}
You can deserialize as Dictionary<string,List<CarDetails>>
public class CarDetails
{
public List<string> HORSEPOWER { get; set; }
public List<string> COLOR { get; set; }
}
and then iterate the dictionary to get the results.
Related
I just want to get this JSON into some kind of object. JArray and JToken are completely confusing to me.
I can create a class so that Newtonsoft knows what to map to but if you will notice the objects have the structure of: { "anAnimal": { foo: 1, bar: 2 }} and I don't know what that mapper object will look like. I'm pretty sure this should just work instantly with zero thought on my part.
var myFavoriteAnimalsJson = #"
[
{
""Dog"": {
""cuteness"": ""7.123"",
""usefulness"": ""5.2"",
}
},
{
""Cat"": {
""cuteness"": ""8.3"",
""usefulness"": ""0"",
}
}
]";
var jArray = new JArray(myFavoriteAnimalsJson);
// grab the dog object. or the cat object. HOW CUTE IS THE DOG?
With .SelectToken() to construct the JSON path query logic.
The below sample to query the first item of animals to get the object of "Dog" token and its value.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
JArray animals = JArray.Parse(myFavoriteAnimalsJson);
var dog = animals[0].SelectToken("Dog");
Console.WriteLine(dog);
Console.WriteLine(dog["cuteness"]);
Sample Program
Output
{
"cuteness": "7.123",
"usefulness": "5.2"
}
7.123
You can deserialize it to a List<Dictionary<string, AnimalData>>
class AnimalData
{
public decimal cuteness;
public decimal usefulness;
}
var myFavoriteAnimalsJson = #"
[
{
""Dog"": {
""cuteness"": ""7.123"",
""usefulness"": ""5.2"",
}
},
{
""Cat"": {
""cuteness"": ""8.3"",
""usefulness"": ""0"",
}
}
]";
var results = JsonConvert.DeserializeObject<List<Dictionary<string, AnimalData>>>(myFavoriteAnimalsJson);
Now each list item contains a dictionary with a single key of Dog Cat...
If you start from a serialized JSON, i.e. a string, you have to parse it:
var jArray = JArray.Parse(myFavoriteAnimalsJson);
I need to deserialize just part of a JSON string returned from a server. The 'myData' portion in the JSON string below.
My JSON string is structured as follows.
{
"data": {
"CODE": {
"someData": {
"h": "foo",
"id": "City",
"lat": "11.11111"
},
"feedMe": [
[
{
"myData": {
"item1": "a",
"item2": "b",
"item3": "c"
},
"moreData": {}
}
]
]
}
}
}
In Unity there is the JSONutility.FromJson method
https://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html
but unsure how I would either
1 pass only the 'myData' portion to this method.
or
2 Deserialize the entire string
An alternativ to using JsonUtility there is good old SimpleJSON which allows you to only access a certain field of your json like e.g.
var N = JSON.Parse(the_JSON_string);
var myData = N["data"]["CODE"]["feedMe"][0][0];
var item2 = myData["item2"].Value;
In general the simplest way to get the needed c# class structure for your json is always using json2csharp and make all classes [Serializable] and remove the {get; set;} in order to use fields instead of properties. Something like this
[Serializable]
public class SomeData
{
public string h;
public string id;
public string lat;
}
[Serializable]
public class CODE
{
public SomeData someData;
public List<List<MyData>> feedMe;
}
[Serializable]
public class MyData
{
public string item1;
public string item2;
public string item3;
}
[Serializable]
public class Data
{
public CODE CODE;
}
[Serializable]
public class RootObject
{
public Data data;
}
Instead of List<T> you can also use T[] if you like. And the class names actually don't matter but the structure and field names have to match.
and then use
var root = JsonUtility.FromJson<RootObject>(THE_JSON_STRING);
var myData = root.data.CODE.feedMe[0][0];
var item2 = myData.item2;
As already comented however there is a nested array in your array .. not sure if this is intended.
well, use one of the powerful json nuget -newtonsoft.json , then in your code you can iterate the values like below
var files = JObject.Parse(YourJSON);
var recList = files.SelectTokens("$..data").ToList();
foreach (JObject obj in recList.Children())
{
foreach (JProperty prop in obj.Children())
{
var key = prop.Name.ToString();
var value = prop.Value.ToString();
//Do your stuffs here
}
}
JsonUtility not work whit json files, this only for save and load basic public variables of some class. Asset Store have many frameworks for parse json. p.s. your json is strange, [] its array and you have feedMe:[[{myData, moreData}]]. One array whene just one object in array... parse confusing.
Using the JSON library, I've imported an array of objects:
dynamic serviceList = JsonConvert.DeserializeObject(listString)
I've got an array of json objects, each has the property "name".
[
{
"name":"abcd",
"properties":{
"type":"1234"
}
},
{
"name":"xyz",
"properties":{
"type":"aaaa"
}
}
]
How do I address just the object "abcd"?
You can parse your json Array using Newtonsoft.Json JArray.Parse() function.
Use FirstOrDefault() to get record where name is "abcd"
string listString = #"[{'name': 'abcd','properties': {'type': '1234'}},{'name': 'xyz', 'properties': { 'type': 'aaaa'}}]";
JArray jArray = JArray.Parse(listString);
//FirstOrDefault to get first record which satisfy the condition
var result = jArray.FirstOrDefault(x => (string)x["name"] == "abcd");
Console.WriteLine(result);
Output:
{
"name": "abcd",
"properties": {
"type": "1234"
}
}
.Net Fiddle
The right way to solve the problem is create a static Object
Public Obj1 {
public string name {get;set;}
public Properties properties {get;set;}
}
Public Properties {
public string type {get;set;}
}
Then you can deserialize the JSON into a List<Obj1>, in this way you can iterate your list and find the "name":"abcd" Object. var myobj = mylist.FirstOrDefault(x=> x.name == "abcd")
You can use the dynamic to do pretty much anything you would like it to do, so nothing would stop you from evaluating your result in the following way:
dynamic selectionList = JsonConvert.DeserializeObject( json );
foreach (var item in selectionList) {
if ( string.Equals( (string)item.name, "abcd", StringComparison.OrdinalIgnoreCase ) ) {
Console.WriteLine( item );
}
}
This would work as per your original request, but I think you are making it a lot harder on yourself than need be :)
To see how this works, you could check this dotnetfiddle
I would probably create a class based on the spec, but I am assuming that properties is a dynamic list of properties and their values, meaning you would still end up with a Dictionary<string, object> in the end
You can access it like this:
for (int i = 0; i < serviceList.Count; i++)
{
if (serviceList[i].name == "abc")
{
DoSomethingWith(serviceList[i];
break;
}
}
Edit: didn't see that you wanted the "abc" element, so modified the code accordingly.
This will get the value for you as a JObject, from which you can access the contained values:
var serviceList = JArray.Parse(listString);
var target = serviceList.Single(s => s["name"].ToString() == "abcd");
if (target != null)
{
var type = target["properties"]["type"];
// etc
}
I am stuck while returning api result, I have a class like
public partial class Sample
{
[JsonProperty("classificator")]
public List<Classificator> Classificator { get; set; }
}
public partial class Classificator
{
[JsonProperty("Value")]
public string Value { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
}
Let's say GetJson method retrieve our data from the database, there are 2 records and the data like
-- Value - Description
1- A - AXA
2- B - BXA
response = GetJson(); // this method gets data from db
return Content(HttpStatusCode.OK, response);
when I return this, it's like
{
"classificator": [{
"Value": "A",
"Description": "AXA"
}, {
"Value": "B",
"Description": "BXA"
}
]
}
but I would like to see like, I want to see bellowing result;
{
"classificator": [{
"A": "AXA"
}, {
"B" : "BXA"
}
]
}
I would like to ask you maybe someone knows a good practice or document(tutorial) about it.
I solve it by using, Dictionary < string, model >
but I need to return a huge nested field I cant implement this solution for all different nodes.
I solved by using Dictionary< string, object >
I put 2 nested objects inside of an object value. In my case it looked some complex I refactor and try to work through readable dictionary hierarchy.
basically for this example it something like below,
Dictionary<string, object> fooDict = new Dictionary<string, object>();
fooDict.Add("A", "AXA"); // in my case I put 2 nested object to value field
fooDict.Add("B", "BXA");
var serializedObject = JsonConvert.SerializeObject(fooDict);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\xxx\result.txt", true))
{
file.WriteLine(serializedObject);
}
I have some JSON with Two objects and these each have 3 objects nested.
{
"FirstPerson": {
"number": "101",
"a10": "1001",
"a20": "1002"
},
"SecondPerson": {
"number": "102",
"a10": "2001",
"a20": "2001"
}
}
In c# asp.net mvc2 I've been able to get to "FirstPerson" or "SecondPerson" using a Hashtable but how do I get to "number" or "a10" when I know "FirstPerson"?
e.g. an objects inside an object.
Is a Hashtable the best use for this or should I be using something else?
Thanks in advance.
I found that solution for your problem may be give a clue to solve that
Want to convert a C# object into it's JSON equivalent? Here is a simple object from the System.Web.Script namespace that does exactly that:
System.Web.Script.Serialization.JavaScriptSerializer . It is stored in the System.Web.Extentions DLL (.Net Framework 3.5 only)
Using this object we serialize and deserialize objects in C#. Here is a quick sample:
A simple Employee object:
public class Employee
{
public string Name { get; set; }
public string Age { get; set; }
public string ID { get; set; }
}
Adding some instances of them to a List:
Employee oEmployee1 =
new Employee{Name="Pini",ID="111", Age="30"};
Employee oEmployee2 =
new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" };
Employee oEmployee3 =
new Employee { Name = "Yoni", ID = "Biton", Age = "20" };
List oList = new List()
{ oEmployee1, oEmployee2, oEmployee3 };
Serializing then:
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);
And here is the output:
[{"Name":"Pini","Age":"30","ID":"111"},
{"Name":"Yaniv","Age":"31","ID":"Cohen"},
{"Name":"Yoni","Age":"20","ID":"Biton"}]
For your consideration here is the link http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/12/convert-objects-to-json-in-c-using-javascriptserializer.aspx
I have had good results using JsonConvert. It seems to do a good job of knowing what to do with collections. Just define the class you want to de-serialize to and have at it.
http://james.newtonking.com/projects/json-net.aspx
Example:
MyCollection col = JsonConvert.DeserializeObject<MyCollection>(this.HttpContext.Request.Params[0]);
Where MyCollection is a class which contains a collection of, in your case, people.
You could assign the JSON object to a dynamic variable and access the properties that way (only in C# 4.0 though)
dynamic jsonData = jsonObject;
int workflowNum = jsonData.SecondPerson[0].workflow;