How make array insert array json in web service C# - c#

How can I create a JsonArray with a child data object array? I am using Web service and C#.
I want the result of the JsonArray to look like the following:
[{
"name": "Deadpool",
"url": {
"small": "http://api.android.info/images/small/deadpool.jpg",
"medium": "http://api.android.info/images/medium/deadpool.jpg",
"large": "http://api.android.info/images/large/deadpool.jpg"
},
"time": "February 12, 2016"
},
{
"name": "The Jungle Book",
"url": {
"small": "http://api.android.info/images/small/book.jpg",
"medium": "http://api.android.info/images/medium/book.jpg",
"large": "http://api.android.info/images/large/book.jpg"
},
"time": "April 15, 2016"
},
{
"name": "X-Men: Apocalypse",
"url": {
"small": "http://api.android.info/images/small/xmen.jpg",
"medium": "http://api.android.info/images/medium/xmen.jpg",
"large": "http://api.android.info/images/large/xmen.jpg"
},
"time": "May 27, 2016"
}]

First, create the models that can output the given data. You need a MovieModel, a movie can have multiple image sizes and urls stored, we use a dictionary for this.
UPDATED
MovieModel.cs
public class MovieModel
{
public string Name { get; set; }
public Dictionary<string,string> Url { get; set; }
public string Time { get; set; }
}
Now you need to install Newtonsoft.Json from Nuget packages. Then import it.
using Newtonsoft.Json;
Initialize the model and convert to Json using SerializeObject() method.
var movieList = new List<MovieModel>
{
new MovieModel
{
MovieName = "Deadpool",
Time = DateTime.UtcNow.ToString("t"),
Url = new Dictionary<string, string>
{
{ "small", "http://api.android.info/images/small/deadpool.jpg" },
{ "medium", "http://api.android.info/images/medium/deadpool.jpg" }
}
}
// .. add more movies .. //
};
// convert to camelcase and set indentation
var output = JsonConvert.SerializeObject(
movieList,
Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
);
// testing output on console
Console.WriteLine(output);
In a real application, you would create Movie instances by getting data from a database, not initializing it for yourself as used in this example.

Related

serilization daughter classes

I am trying to serialize a class that has daughter classes but it does not allow me when I go to complete the json it gives me an error
This is the json file as it should look:
{
"User": "jhuan.caasillas",
"Passwd": "#########",
"IdAplicativo": 2001,
"Firma": "asdlkhg=saldkja=="
}
"Mensaje": {
"CodigoMensaje": 320,
"DescMensaje": "Exito"
},
"Roles": [
{
"Descripcion": "juan casillas"
},
{
"Descripcion": "al21"
},
{
"Descripcion": "comandos"
},
{
"Descripcion": "identificado"
}
]
}
I have this class with these methods created
enter image description here
when I go to fill these methods with the json it doesn't allow me and I get the error
Cannot implicitly convert type 'serialize.Roles' to 'serialize.Roles[]' serialize
enter image description here
I would like to know how I can fill the json array that I showed previously
If Roles is array it must be initialized as array
DominioRes res1 = new DominioRes
{
Roles = new Roles[]
{
new Roles
{
Description="juan casillas"
},
new Roles
{
Description="al21"
},
new Roles
{
Description="comandos"
},
new Roles
{
Description="identificado"
}
}
};

Selected JSON data to c# object [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 8 months ago.
{
"name": "India",
"topLevelDomain": [".in"],
"alpha2Code": "IN",
"alpha3Code": "IND",
"callingCodes": ["91"],
"capital": "New Delhi",
"altSpellings": ["IN", "Bhārat", "Republic of India", "Bharat Ganrajya"],
"subregion": "Southern Asia",
"region": "Asia",
"population": 1380004385,
"latlng": [20.0, 77.0],
"demonym": "Indian",
"area": 3287590.0,
"gini": 35.7,
"timezones": ["UTC+05:30"],
"borders": ["AFG", "BGD", "BTN", "MMR", "CHN", "NPL", "PAK", "LKA"],
"nativeName": "भारत",
"numericCode": "356",
"flags": {
"svg": "https://flagcdn.com/in.svg",
"png": "https://flagcdn.com/w320/in.png"
},
"currencies": [{ "code": "INR", "name": "Indian rupee", "symbol": "₹" }],
"languages": [
{
"iso639_1": "hi",
"iso639_2": "hin",
"name": "Hindi",
"nativeName": "हिन्दी"
},
{
"iso639_1": "en",
"iso639_2": "eng",
"name": "English",
"nativeName": "English"
}
],
"translations": {
"br": "Índia",
"pt": "Índia",
"nl": "India",
"hr": "Indija",
"fa": "هند",
"de": "Indien",
"es": "India",
"fr": "Inde",
"ja": "インド",
"it": "India",
"hu": "India"
},
"flag": "https://flagcdn.com/in.svg",
"regionalBlocs": [
{
"acronym": "SAARC",
"name": "South Asian Association for Regional Cooperation"
}
],
"cioc": "IND",
"independent": true
}
This is my JSON data.From this I need to convert
name
population
area
altSpellings
these values to c#
Using the Newtonsoft.Json library you can load the JSON content into a JObject and treat it like a dictionary where the property names are the key values like so:
//Load the JSON into a JObject
var json = ...
var jsonObject = JObject.Parse(json);
//Pull out the property values using the name as a key
var name = jsonObject["name"].ToString();
var population = int.Parse(jsonObject["population"].ToString());
var area = jsonObject["area"].ToString();
var altSpellings = new List<string>();
foreach (var altSpelling in (JArray)jsonObject["altSpellings"])
altSpellings.Add(altSpelling.ToString());
This is a quick way to get the values out without having to create concrete types to deserialise into. If you happen to have a class that maps onto this JSON structure (json2csharp can be handy here) then you could instead use JsonConvert.DeserializeObject<T> instead to deserialise into an instance of that type where you can access the fields directly.
you can create a class with the properties you need
using Newtonsoft.Json;
Data data = JsonConvert.DeserializeObject<Data>(json);
string name = data.Name; // India
result
{
"name": "India",
"population": 1380004385,
"area": 3287590,
"altSpellings": [
"IN",
"Bhārat",
"Republic of India",
"Bharat Ganrajya"
]
}
class
public partial class Data
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("population")]
public long Population { get; set; }
[JsonProperty("area")]
public long Area { get; set; }
[JsonProperty("altSpellings")]
public List<string> AltSpellings { get; set; }
}

deserialize a dynamic json object to a class

I'm working with an external API to get some product information, the end points return some data in a static structure and others in dynamic depending on the product I'm inquiring.
For example if I'm requesting data for a soap I get the following JSON:
{ "id": 4623,
"brand": "Fa",
"category": "Cleansing/Washing/Soap – Body",
"photos": {
"name": "Photos",
"value": [ "https//test.com/1jpg"
]
},
"productname": {
"name": "Product Name",
"value": "Fa Shower Cream Yoghurt Vanilla Honey"
},
"warningstatement": {
"name": "Warning Statement",
"value": "Avoid contact with eyes."
},
"consumerusageinstructions": {
"name": "Consumer Usage Instructions",
"value": "Apply directly on skin."
}
and if I'm inquiring about a cheese I get the following JSON:
{
"id": 10838,
"brand": "Domty",
"category": "Cheese",
"photos": {
"name": "Photos",
"value": [ "https://test.com/2.jpg"
]
},
"productname": {
"name": "Product Name",
"value": "Domty White Low Salt Cheese"
},
"description": {
"name": "1312",
"value": "Highest premium quality"
},
"netcontent": {
"name": "Net Content",
"value": "900 gm"
}
and it goes on for every product they offer. I've no problem deserializing the static data like photos array, product name, brand, and id since they are applicable to every product, but the other dynamic properties are the ones I'm concerned about. Is there a way to deserialize to a class like this:
public class Info {
property string key { get; set;} // to hold description, consumerusageinstructions or what every key
property string name { get; set;}
property string value { get; set;}
}
and then add a collection of the class info to my product model?
One way is just to parse the Json and look at the actual entities: this example uses Json.Net:
var parsed = JObject.Parse(json);
var properties = parsed.Children().Cast<JProperty>();
foreach (var property in properties) {
// an alternative here would be to just have a list of names to ignore
if (!(property.Value is JObject jObject)) {
// skip the simple property/value pairs
continue;
}
if (property.Name == "productname") {
// skip product name
continue;
}
if (property.Value["value"] is JArray) {
// skip photos
continue;
}
// Add to ProductModel instance
Console.WriteLine($"{property.Name} => {property.Value["name"]} = {property.Value["value"]}");
}
Outputs:
warningstatement => Warning Statement = Avoid contact with eyes.
consumerusageinstructions => Consumer Usage Instructions = Apply directly on skin.
description => 1312 = Highest premium quality
netcontent => Net Content = 900 gm

Deserialize JSON to nested classes with ReactiveProperty fields

I'm calling an API endpoint that return me a JSON some data and I need to deserialize it into classes and nested classes that may contains ReactiveProperty fields ( a type coming from UniRx library which is a reimplemntation of Reactive extensions for Unity3D ).
I'm new to C#, I tried some things, but I can't achieve it the way i want.
Here is the json returned by my Api ( in reality there are more data but this example will suffice ) :
"user": {
"id": "87f2ae6e-af99-4f8e-9d69-08de6ad6baf8",
"username": "test",
"email": "test#test.com",
"money": 800,
"morale": 100,
"health": 100,
"credits": 15,
"energy": 100,
"banned_at": null,
"last_connection": null,
"officers": [
{
"id": "2b72d9d4-635c-4b32-9575-5df49f566e93",
"name": "David Le Salmon",
"is_available": true,
"age": 42,
"condition": 100,
"user_id": "87f2ae6e-af99-4f8e-9d69-08de6ad6baf8"
},
{
"id": "ebc4074c-7b94-4ea3-96d9-f80608972afa",
"name": "Philippe Mercier",
"is_available": true,
"age": 34,
"condition": 100,
"user_id": "87f2ae6e-af99-4f8e-9d69-08de6ad6baf8"
},
{
"id": "edba67b5-9053-4fd6-b64e-6b85f4d0cc25",
"name": "Raymond Wagner-Berthelot",
"is_available": true,
"age": 55,
"condition": 100,
"user_id": "87f2ae6e-af99-4f8e-9d69-08de6ad6baf8"
}
],
"vehicles": [
{
"id": "3161d274-ed2a-491b-8515-beb7da9bfd29",
"mileage": 0,
"health": 100,
"level": 3,
"equipment_level": 4,
"vehicle_prefab_id": "14e8d96f-0e85-40ad-b01b-5f00a37b1108"
},
{
"id": "ff984c79-4511-4ade-92d1-9bf6899a243c",
"mileage": 0,
"health": 100,
"level": 4,
"equipment_level": 4,
"vehicle_prefab_id": "14e8d96f-0e85-40ad-b01b-5f00a37b1108"
}
]
}
}
I defined some classes like this :
[Serializable]
public class AppState {
public User user = new User();
}
[Serializable]
public class User {
public string username;
public string email;
public ReactiveProperty<int> money = new ReactiveProperty<int>();
public ReactiveProperty<int> morale = new ReactiveProperty<int>();
public ReactiveProperty<int> health = new ReactiveProperty<int>();
public ReactiveProperty<int> energy = new ReactiveProperty<int>();
public List<Officer> officers = new List<Officer[]>();
public List<Vehicles> vehicles = new List<Vehicle>();
}
Officer and Vehicle are defined in the same way, some fields are ReactiveProperty, some not.
And here how I tried to deserialize :
RestClient.Get("/getAppState").Then(response => {
var stuff = JsonConvert.DeserializeObject<AppState>(response.Text);
})
This code throws this error :
Could not cast or convert from System.String to UniRx.ReactiveProperty
I found something that "work", I assigned all ReactiveProperty fields manually, but it's really tedious.
Is there a way to do this in C#?
Make the Reactive property fields NonSerializable.
Make new serializable String fields.
Deserialize the JSON.
Add some functions to your class(es) that cast the string representations into your ReactiveProperty variables.
Call those functions after you desierialize your JSON.
Note: I am unfamiliar with ReactiveProperty, you'll need to investigate that library to find the best way of casting a string into those objects.

Search for a nested value inside of a JSON.net object in C#

I've got a JSON stream coming back from a server, and I need to search for a specific value of the node "ID" using JSON.net to parse the data.
And I can almost make it work, but not quite because the results coming back are deeply nested in each other -- this is due to the fact that I'm getting a folder structure back. I've boiled the JSON down to a much simpler version. I'm getting this:
{
"data": {
"id": 0,
"name": "",
"childFolders": [{
"id": 19002,
"name": "Locker",
"childFolders": [{
"id": 19003,
"name": "Folder1",
"childFolders": [],
"childComponents": [{
"id": 19005,
"name": "route1",
"state": "STOPPED",
"type": "ROUTE"
}]
}, {
"id": 19004,
"name": "Folder2",
"childFolders": [],
"childComponents": [{
"id": 19008,
"name": "comm1",
"state": "STOPPED",
"type": "COMMUNICATION_POINT"
}, {
"id": 19006,
"name": "route2",
"state": "STOPPED",
"type": "ROUTE"
}, {
"id": 19007,
"name": "route3",
"state": "STOPPED",
"type": "ROUTE"
}]
}],
"childComponents": []
}],
"childComponents": []
},
"error": null
}
I can almost get there by going:
var objects = JObject.Parse(results);
var subobjects = objects["data"]["childFolders"][0]["childFolders"][1];
I can see in the debug view that it'll parse the object, but won't let me search within.
My ultimate goal is to be able to search for "route3" and get back 19007, since that's the ID for that route. I've found some results, but all of them assume you know how far nested the object is. The object I'm searching for could be 2 deep or 20 deep.
My ultimate goal is to be able to search for "route3" and get back 19007
You can use linq and Descendants method of JObject to do it:
var dirs = JObject.Parse(json)
.Descendants()
.Where(x=>x is JObject)
.Where(x=>x["id"]!=null && x["name"]!=null)
.Select(x =>new { ID= (int)x["id"], Name = (string)x["name"] })
.ToList();
var id = dirs.Find(x => x.Name == "route3").ID;
You can use the SelectToken or SelectTokens functions to provide a JPath to search for your desired node. Here is an example that would provide you the route based on name:
JObject.Parse(jsonData)["data"].SelectToken("$..childComponents[?(#.name=='route3')]")
You can find more documentation on JPath here
Simply write a recursive function:
private Thing FindThing(Thing thing, string name)
{
if (thing.name == name)
return thing;
foreach (var subThing in thing.childFolders.Concat(thing.childComponents))
{
var foundSub = FindThing(subThing, name);
if (foundSub != null)
return foundSub;
}
return null;
}
class RootObject
{
public Thing data { get; set; }
}
class Thing
{
public int id { get; set; }
public string name { get; set; }
public List<Thing> childFolders { get; set; } = new List<Thing>();
public List<Thing> childComponents { get; set; } = new List<Thing>();
}
And using it:
var obj = JsonConvert.DeserializeObject<RootObject>(jsonString);
var result = FindThing(obj.data, "route3");

Categories

Resources