How to Convert JSON object to Array - c#

I am new to C# need help to convert json Object to Array
convert this json
[
{
"Id": 1000,
"Name": "May",
"Address": "odyssey",
"Country": "USA",
"Phone": "12345"
}
]
To
var details = {1000,May,odyssey,USA,12345};

Use Newtonsoft.Json to deserialize JSON to a specified .net type. You can deserialize to a class too, see below:
public class Person
{
public int Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public string Phone {get;set;}
}
var details = JsonConvert.DeserializeObject<Person>(json);

You are going to have to deserialize the Json String. Deserialize into array of objects.
JavaScriptSerializer js = new JavaScriptSerializer();
yourClass[] items = js.Deserialize<Yourclass[]>(yourJSONcontent);

Steps:
1. Create Model.
2. Get Data in string
3.Deserialize Object
And if you are confused How to create C# model from the json then use this link.
https://app.quicktype.io
Use This Model.
public class Test
{
[JsonProperty("Id")]
public long Id { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Address")]
public string Address { get; set; }
[JsonProperty("Country")]
public string Country { get; set; }
[JsonProperty("Phone")]
[JsonConverter(typeof(ParseStringConverter))]
public long Phone { get; set; }
}
string data="Your Json String"
var details = JsonConvert.DeserializeObject<Test>(data);

To make a list from your json values you can use a JObject, you don't have to know the objects stored in your Json in contrary to the others question.
JObject myObject = JsonConvert.DeserializeObject<JObject>(myJson);
List<object> myList = new List<object>();
foreach (var element in myObject)
{
myList.Add(element.Value);
}
If you already know what your json is made of, you can create a class that represent your object and implement the interface IEnumerable.
var myObject = JsonConvert.DeserializeObject<MyClass>(myJson);
var myArray = myObject2.ToArray():
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public int Phone { get; set; }
public object[] ToArray()
{
return new object[]
{
Id,
Name,
Address,
Country,
Phone
};
}
}
NB : the variable myJson in the previous codes is a string that represent your json as var myJson = "{\"Id\": 1000,\"Name\": \"May\",\"Address\": \"odyssey\",\"Country\": \"USA\",\"Phone\": \"12345\"}";

Related

convert array in json to c# dictionary

i have this json string:
{"products": [{"id": 22,"date_add": "2021-06-17 19:21:26","date_upd": "2021-07-12 13:02:01","name": [{"id": "1","value": "Product 1"}, {"id": "2", "value": "Product 1"}]}}, {"id": 1,"date_add": "2021-06-17 18:54:54","date_upd": "2021-06-17 18:54:54","name": [{"id": "1","value": "something321"},{"id": "2","value": "something23"}]}]}
and this class:
class Products
{
[JsonProperty("id")]
public override string ExternalId { get; set; }
[JsonProperty("name")]
public Dictionary<string, string> Name { get; set; }
[JsonProperty("date_upd")]
public DateTime DateModified{ get; set; }
}
i want to map my json products to List of Products, so I tried this:
// get "products" array from json
Regex regex = new Regex(#"(?:{""products"":)(.+)(?:})");
MatchCollection matches = regex.Matches(result);
if (matches.Count > 0)
{
result = matches[0].Groups[1].Value;
}
else
{
result = null;
}
//
var deserialized = JsonConvert.DeserializeObject<List<PrestaProducts>>(result);
it throws: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. ...
ok - if i set type of name to object, it works correct and set the list of anon objs.
( public object Name { get; set; } )
but how can i set that names to dictionary?
What I see from your example, you cannot convert name to Dictionary<string, string> since it's array.
However you can do something like this. Change this line to include List:
var deserialized = JsonConvert.DeserializeObject<List<Products>>(result);
and change your model to something like this:
public class Products
{
[JsonProperty("id")]
public string ExternalId { get; set; }
[JsonProperty("name")]
public List<Dictionary<string, string>> Name { get; set; }
[JsonProperty("date_upd")]
public DateTime DateModified { get; set; }
}
I don't know if this is what you expected or wanted but at least you will fix the error you have at the moment.
To me it does not make much sense to have dictionary inside list but you cannot directly convert array to dictionary in a way you tried.
You can convert it to list products
var jsonObj = JsonConvert.DeserializeObject<JsonObjects>(json);
var productObjects = jsonObj.products;
if you want to convert it to dictionary, try this:
var products = new Products { products = new List<Product> { } };
foreach (var item in productObjects)
{
var product = new Product
{
id = item.id,
date_add = item.date_add,
date_upd = item.date_upd,
name=new Dictionary<string,string>()
};
foreach (var name in item.name)
{
product.name.Add(name.id,name.value);
}
products.products.Add(product);
}
var productsJson= JsonConvert.SerializeObject( products);
OUTPUT
{"products":[
{"id":22,"date_add":"2021-06-17 19:21:26","date_upd":"2021-07-12 13:02:01",
"name":{"1":"Product 1","2":"Product 1"}},
{"id":1,"date_add":"2021-06-17 18:54:54","date_upd":"2021-06-17 18:54:54",
"name":{"1":"Hummingbird printed t-shirt","2":"Hummingbird printed t-shirt"}}
]}
classes
public class Name
{
public string id { get; set; }
public string value { get; set; }
}
public class JsonProduct
{
public int id { get; set; }
public string date_add { get; set; }
public string date_upd { get; set; }
public List<Name> name { get; set; }
}
public class JsonObjects
{
public List<JsonProduct> products { get; set; }
}
public class Product
{
public int id { get; set; }
public string date_add { get; set; }
public string date_upd { get; set; }
public Dictionary<string, string> name { get; set; }
}
public class Products
{
public List<Product> products { get; set; }
}

How can I convert a json string to a json array using Newtonsoft?

I am using this code to read a json file firstSession.json and display it on a label.
var assembly = typeof(ScenarioPage).GetTypeInfo().Assembly;
string jsonFileName = "firstSession.json";
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{jsonFileName}");
using (var reader = new StreamReader(stream))
{
var json = reader.ReadToEnd(); //json string
var data = JsonConvert.DeserializeObject<SessionModel>(json);
foreach (SessionModel scenario in data)
{
scenarioName.Text = scenario.title;
break;
}
scenarioName.Text = data.title; // scenarioName is the name of the label
}
SessionModel.cs looks like:
public class SessionModel : IEnumerable
{
public int block { get; set; }
public string name { get; set; }
public string title { get; set; }
public int numberMissing { get; set; }
public string word1 { get; set; }
public string word2 { get; set; }
public string statement1 { get; set; }
public string statement2 { get; set; }
public string question { get; set; }
public string positive { get; set; } // positive answer (yes or no)
public string negative { get; set; } // negative answer (yes or no)
public string answer { get; set; } // positive or negative
public string type { get; set; }
public string format { get; set; }
public string immersion { get; set; }
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
The beginning of my json is:
{
"firstSession": [
{
"block": 1,
"name": "mark",
"title": "mark's house",
"numberMissing": 1,
"word1": "distracted",
"word2": "None",
"statement1": "string 1",
"statement2": "None",
"question": "question",
"positive": "No",
"negative": "Yes",
"answer": "Positive",
"type": "Social",
"format": "Visual",
"immersion": "picture"
},
I am getting a Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object into type "MyProject.SessionModel" because the type requires a JSON array to deserialize correctly. To fix this error either change the JSON to a JSON array or change the deserialized type so that it is a normal .NET type that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'firstSession', line 2, position 17.
How can I convert the json string to a json array? Or make one of the other modifications the debugger suggests?
you need to create a wrapper class (json2csharp.com will help you do this)
public class Root {
public List<SessionModel> firstSession { get; set; }
}
then
var data = JsonConvert.DeserializeObject<Root>(json);
data.firstSession will be a List<SessionModel>
Create a new Class and have firstSession as List of SessionModel.
public class Sessions
{
public List<SessionModel> firstSession { get; set; }
}
Remove IEnumerable from the SessionModel
public class SessionModel
{
public int block { get; set; }
public string name { get; set; }
public string title { get; set; }
}
Change thedeserialization part as follows
var data = JsonConvert.DeserializeObject(line);
foreach (SessionModel scenario in data.firstSession)
{
//Here you can get each sessionModel object
Console.WriteLine(scenario.answer);
}

Adding JArray to an existing property

I have this JSON:
{
"ID":123,
"Products":null,
"Title":"Products"
}
I want to add some data from DB to the "Products" node so my final json will look like so:
{
"ID":123,
"Products":[
{
"ID":1,
"Name":"AA"
},
{
"ID":2,
"Name":"BB"
}
],
"Title":"Products"
}
I'm using this code:
internal class Product
{
public int ID { get; set; }
public string Name { get; set; }
}
//simulate DB
var products= new List<Product>()
{
new Product() {ID=1,Name="AA" },
new Product() {ID=2,Name="BB" }
};
string JSONstr = FilesUtils.OpenFile(Path.Combine(Environment.CurrentDirectory, "Sample.json"));
JObject JSON = JObject.Parse(JSONstr);
((JValue)JSON["Products"]).Value = JObject.FromObject(products);
But I get an exception:
Object serialized to Array. JObject instance expected.
You can do:
JSON["Products"] = JToken.FromObject(products);
To add a new property, do the same thing, e.g.:
JSON["TimeStamp"] = JToken.FromObject(DateTime.UtcNow);
Notes:
The item setter for JObject will add or replace the property with the specified name "Products".
JToken.FromObject() serializes any .Net object to a LINQ to JSON hierarchy. JToken is the abstract base class of this hierarchy and so can represent both arrays, objects, and primitives. See here for details.
Sample fiddle.
The expected object will have to be (according to your JSON). If that's the JSON you want you might consider wrapping it up and adding the ID and a Title as shown in the JSON.
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
}
public class YourObject
{
public int ID { get; set; }
public List<Product> Products { get; set; }
public string Title { get; set; }
}

JSON model binding with variable keys .net mvc4

What is a useful model which could bind a json object with arbitrary keys? Assume your json could look like:
{"##hello": "address","#world": "address1","name": "address"}
or
{"##hello": "address","#world": "address1","firstname": "foo", "lastname":"bar"}
or
{"##hello": "address","#world": "address1","children": [{"name":"foo"},{"name":"bar"}]}
So that means you only know at run time how the json model looks like. My current state is, that it seems the best practice is to send the json object as string to the controller and deserialize the json string it to an object.
public ActionResult mappingNodes(string model) {
dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(model);
}
public class Children
{
[JsonProperty("name")]
public string Name { get; set; }
}
public class YourClass
{
[JsonProperty("##hello")]
public string Hello { get; set; }
[JsonProperty("#world")]
public string World { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("firstname")]
public string FirstName { get; set; }
[JsonProperty("lastname")]
public string LastName { get; set; }
[JsonProperty("children")]
public Children[] Children { get; set; }
}
var json1 = "{ '##hello': 'address','#world': 'address1','name': 'address'}";
var json2 = "{ '##hello': 'address','#world': 'address1','name': 'address', 'firstname': 'foo', 'lastname':'bar'}";
var json3 = "{ '##hello': 'address','#world': 'address1','name': 'address','children': [{'name':'foo'},{'name':'bar'}]}";
var model1 = JsonConvert.DeserializeObject<YourClass>(json1);
var model2 = JsonConvert.DeserializeObject<YourClass>(json2);
var model3 = JsonConvert.DeserializeObject<YourClass>(json3);

How to Convert Json Object to Array in C#

I am trying to convert a JSON object in to C# array.
this is the JSon I Getfrom the Server webrequest response:
string result = sr.ReadToEnd(); // this line get me response
result = {
"subjects": [{
"subject_id": 1,
"subject_name": "test 1",
"subject_class": 4,
"subject_year": "2015",
"subject_code": "t-1"
},{
"subject_id": 2,
"subject_name": "test 2",
"subject_class": 5,
"subject_year": "",
"subject_code": "t-2"
}]
};
dynamic item = JsonConvert.DeserializeObject<object>(result);
string iii = Convert.ToString(item["subjects"]);
I want to Get the Subjects and Save them in Array so i can use them for other purpose.
I use these to Method but always got the empty values.
List<subjects> subject1 = (List<subjects>)JsonConvert.DeserializeObject(iii, typeof(List<subjects>));
and
subjects[] subject2 = JsonConvert.DeserializeObject<subjects[]>(iii);
Please Help Me to Solve this.
And my Subject Class is..
class subjects
{
public int id { get; set; }
public string name { get; set; }
public int class_name { get; set; }
public string year { get; set; }
public string code { get; set; }
}
The property names won't match as is, because you subjects class don't have the 'subject_' prefix the JSON object has. Easiest fix is to change your property names as shown in Ali's answer. Just in case you need to keep your property names as is, you can also use a JsonProperty attribute to alter the serialization names (perhaps there's a more generic way using some sort of converter, but didn't think the amount of properties needed it)
class subjects
{
[JsonProperty("subject_id")]
public int id { get; set; }
[JsonProperty("subject_name")]
public string name { get; set; }
[JsonProperty("subject_class")]
public int class_name { get; set; }
[JsonProperty("subject_year")]
public string year { get; set; }
[JsonProperty("subject_code")]
public string code { get; set; }
}
If you never need the root subjects you can also skip it without dynamic or an extra class with something like:
subjects[] arr = JObject.Parse(result)["subjects"].ToObject<subjects[]>();
(JObject is part of the namespace Newtonsoft.Json.Linq )
You need to create a structure like this:
public class Subjects
{
public List<Subject> subjects {get;set;}
}
public class Subject
{
public string subject_id {get;set;}
public string subject_name {get;set;}
}
Then you should be able to do:
Subjects subjects = JsonConvert.DeserializeObject<Subject>(result);

Categories