I want to parse the JSON on the bottom. Till now I always have the static key for the variables, but in this example, the keys are always changing. Here the "58e7a898dae4c" and "591ab00722c9f" could have any value and change constantly. How can I get the value of the elements of the set to be able to reach the PreviewName value?
{
"key": "gun",
"objects": [
{
"name": "AK47",
"sets": {
"58e7a898dae4c": {
"set_id": "58e75660719a9f513d807c3a",
"preview": {
"resource": {
"preview_name": "preview.040914"
}
}
},
"591ab00722c9f": {
"set_id": "58eba618719a9fa36f881403",
"preview": {
"resource": {
"preview_name": "preview.81a54c"
}
}
}
}
}
]
}
public class Object
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("sets")]
public Dictionary<string, Set> Sets { get; set; }
}
public class Set
{
[JsonProperty("set_id")]
public string SetId { get; set; }
[JsonProperty("preview")]
public Preview Preview { get; set; }
}
public class Preview
{
[JsonProperty("resource")]
public ResourcePreview Resource { get; set; }
}
public class ResourcePreview
{
[JsonProperty("preview_name")]
public string PreviewName { get; set; }
}
var root = JsonConvert.DeserializeObject<RootObject>(json);
string previewName1 = root.Objects[0].Sets["58e7a898dae4c"].Preview.Resource.PreviewName;
string previewName2 = root.Objects[0].Sets["591ab00722c9f"].Preview.Resource.PreviewName;
you don't need to deserialize, you can parse
var jsonParsed=JObject.Parse(json);
string[] previewNames= ((JArray)jsonParsed["objects"])
.Select(v => ((JObject)v["sets"]))
.Select(i=>i.Properties().Select(y=> y.Value["preview"]["resource"])).First()
.Select(i=> (string) ((JObject)i)["preview_name"]).ToArray();
result
preview.040914
preview.81a54c
Related
{
"number": 1165,
"lineItems": [{
"itemId": 1,
"dynamicfields": {
"styleId": "V-Neck",
"style": "T-SHIRTS",
"cost": 30
}
},
{
"itemId": 2,
"dynamicfields": {
"styleId": "V-Neck",
"style": "T-SHIRTS",
"cost": 30
}
}]
}
How can I validate dynamic fields for two different item id is same? I need to show validation message saying duplicate dynamic fields should not allow.
I have done some RND but there I am finding for JSON Keys duplication but I need Key Values duplication check.
Here is a demo to check json data.
Models:
public class ModelB{
public int number { get; set; }
public List<LineItem> lineItems { get; set; }
}
public class LineItem
{
public int itemId { get; set; }
public Dynamicfields dynamicfields { get; set; }
}
public class Dynamicfields {
public string styleId { get; set; }
public string style { get; set; }
public int cost { get; set; }
}
Action:
public string CheckRepeat([FromBody]ModelB modelB)
{
for (int i = 0; i < modelB.lineItems.Count() - 1; i++)
{
if (modelB.lineItems.Where(l => JsonConvert.SerializeObject(l.dynamicfields) == JsonConvert.SerializeObject(modelB.lineItems[i].dynamicfields)).Count() > 1)
{
return "duplicate dynamic fields should not allow";
}
}
return "";
}
result:
If you get jsondata,you can convert it to ModelB with:
ModelB modelB=JsonConvert.DeserializeObject<ModelB>(jsondata);
I'm trying to deserialize a json file in c# and print the values of each individual value by using the key, but for the json values that are a list, I'm unable to print the desired values.
Json file:
{
"prod": {
"vpc_name": "vpc-us-east-1-it-prod",
"subnets": {
"application": [ "subnet-1234", "subnet-1345" ],
"data": [ "subnet-64t3", "subnet-f321" ],
"edge": [ "subnet-1ff3", "subnet-134g" ]
}
},
"dev": {
"vpc_name": "vpc-us-east-1-it-dev",
"subnets": {
"application": [
{ "subnet_id": "subnet-2345tf", "az": "us-east-1a" },
{ "subnet_id": "subnet-143f1", "az": "us-east-1b" }
],
"data": [
{ "subnet_id": "subnet-134f", "az": "us-east-1b" },
{ "subnet_id": "subnet-1324", "az": "us-east-1a" }
],
"edge": [
{ "subnet_id": "subnet-123434", "az": "us-east-1a" },
{ "subnet_id": "subnet-123fg", "az": "us-east-1b" }
]
}
}
}
C# code
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
namespace JsonDeserializer
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string jsonString = File.ReadAllText(#"C:/Users/Stephen.Carvalho/source\repos/JsonDeserializer/JsonDeserializer/vpc_stack.json");
Rootobject vpcs = JsonSerializer.Deserialize<Rootobject>(jsonString);
Console.WriteLine(vpcs.dev.vpc_name);
Console.WriteLine(vpcs.dev.subnets.application);
}
}
public class Rootobject
{
public Prod prod { get; set; }
public Dev dev { get; set; }
}
public class Prod
{
public string vpc_name { get; set; }
public Subnets subnets { get; set; }
}
public class Subnets
{
public string[] application { get; set; }
public string[] data { get; set; }
public string[] edge { get; set; }
}
public class Dev
{
public string vpc_name { get; set; }
public Subnets1 subnets { get; set; }
}
public class Subnets1
{
public Application[] application { get; set; }
public Datum[] data { get; set; }
public Edge[] edge { get; set; }
}
public class Application
{
public string subnet_id { get; set; }
public string az0885b3b66d { get; set; }
public string az { get; set; }
}
public class Datum
{
public string subnet_id { get; set; }
public string az { get; set; }
}
public class Edge
{
public string subnet_id { get; set; }
public string az { get; set; }
}
}
Output
Hello World!
vpc-us-east-1-it-dev
JsonDeserializer.Application[]
I want to print the list of application subnets with prod.subnets but instead of getting the values returned I'm getting JsonDeserializer.Application[] as the output
That is because vpcs.dev.subnets.application is an array of Application. You can print the array of application subnets by first getting the subnet_ids then converting that array to a string.
Reason you see JsonDeserializer.Application[] is because your printing the object itself.. when you do that, you get the name of the object type instead of the values inside of it.
Console.WriteLine(string.Join(", ", vpcs.dev.subnets.application.Select(x => x.subnet_id)));
The Select statment goes through each of the application and returns only the subnet_id. Whenever you have an array / list, you can use the select method to get specific items from the list or create new object with this as well.
Documentation on Select
That's happening since you're trying to print an array in an line, you can try doing something like this:
Array.ForEach(vpcs.dev.subnets.application, Console.WriteLine);
or parsing it to a list and printing it
vpcs.dev.subnets.application.ToList().ForEach(i => Console.WriteLine(i.ToString()));
or you can also try doing it in a foreach:
foreach(var item in vpcs.dev.subnets.application)
{
Console.WriteLine(item.ToString());
}
I am confuse with the numbered(the key) newslist (array)
The json string is valid, in nodeJS it managed to output the values that i need.
JSON STRING as is
{
"newsalert": [{
"newslist": {
"1": {
"newsid": "4321",
"headline": "Great White Shark Found",
"newscode": "GWS",
"newstime": "10:04:32"
},
"2": {
"newsid": "8031",
"headline": "Polar Bear Escaped",
"newscode": "PBE",
"newstime": "09:28:03"
}
}
}]
}
C# Code
class MainNews {
public Dictionary<string, newslist[]> newsalert { get; set; }
}
class newslist {
public int newsid { get; set; }
public string headline{ get; set; }
public string newscode { get; set; }
public string newstime { get; set; }
}
static void ShowObject(MainNews obj) {
foreach (var item in obj.news.Values.ElementAt(0)) {
MessageBox.Show(item.headline);
}
}
private void BtnTest_Click(object sender, RoutedEventArgs e) {
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
var xnews = JsonConvert.DeserializeObject<MainNews>(jsonstring);
ShowObject(xnews);
}
Error
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON array because the type requires a JSON object
You are missing a step betwwen your root and the Dictionary.
newsalert is a collection on a object with a property name newslist.
That this is your dictionary.
public class MainNews
{
public List<NewAlert> newsalert { get; set; }
}
public class NewAlert
{
public Dictionary<int, NewItem> newslist { get; set; }
}
public class NewItem
{
public string newsid { get; set; }
public string headline { get; set; }
public string newscode { get; set; }
public string newstime { get; set; }
}
You can simply :
string input = #"{
""newsalert"": [{
""newslist"": {
""1"": {
""newsid"": ""4321"",
""headline"": ""Great White Shark Found"",
""newscode"": ""GWS"",
""newstime"": ""10:04:32""
},
""2"": {
""newsid"": ""8031"",
""headline"": ""Polar Bear Escaped"",
""newscode"": ""PBE"",
""newstime"": ""09:28:03""
}
}
}]
}";
var result = JsonConvert.DeserializeObject<MainNews>(input);
result.newsalert.SelectMany(x=> x.newslist.Values).Dump();
Live Demo: https://dotnetfiddle.net/Ar5ocP
if the key is different, how do i deserialize the JSON file, key from key1 to keyN ? when i using python it's very easy,
import pandas as pd
myJson = pd.json.loads(json)
just used two lines code, but when i use C#, it's very hard to me. thanks.
i tried:
1. visual studio -> Edit -> Paste Special -> Paste Json as Classes, it will generate many class for every item key, which is too bad for me, because my key maybe from key1 to key 1000.
public class Rootobject
{
public Key1 key1 { get; set; }
public Key2 key2 { get; set; }
public Key3 key3 { get; set; }
}
2.now i used below method, but i still think it's not easy as python.
JObject items = JObject.Parse(json);
foreach(var item in items)
{
JObject v = JObject.Parse(item.Value.ToString());
foreach(KeyValuePair<string, JToken> property in v)
{ //do something}
}
json string:
{
"key1":
{
"id":1,
"name":"i",
"AllocationInfo":
{
"State":"Init",
"Name":"test",
"TModel":
{
"Name":"test2",
"key":"1232445",
"v":{
"id":"090",
"Name":"tom"
}
}
}
},
"key2":
{
"id":1,
"name":"i",
"AllocationInfo":
{
"State":"Init",
"Name":"test",
"TModel":
{
"Name":"test2",
"key":"1232445",
"v":{
"id":"090",
"Name":"tom"
}
}
}
},
"key3":
{
"id":1,
"name":"i",
"AllocationInfo":
{
"State":"Init",
"Name":"test",
"TModel":
{
"Name":"test2",
"key":"1232445",
"v": {
"id":"090",
"Name":"tom",
"D":{"id":"7890"}
}
}
}
}
}
Use DeserializeObject and get a dictionary from it:
var r = JsonConvert.DeserializeObject<Dictionary<string, Key>>(txt);
Declare your classes:
public class Key
{
public int id { get; set; }
public string name { get; set; }
public AllocationInfo AllocationInfo { get; set; }
}
public class AllocationInfo
{
public string State { get; set; }
public string Name { get; set; }
public TModel TModel { get; set; }
}
public class TModel
{
public string Name { get; set; }
public string key { get; set; }
public v v { get; set; }
}
public class v
{
public string id { get; set; }
public string name { get; set; }
}
You pasted the entire json when you used the paste special. But I think you only want to generate one class for all your keyN objects. You can then just use Newtonsoft to deserialize the json to a list.
var myKeys = Newtonsoft.Json.JsonConvert.DeserializeObject<List<KeyN>>(json);
I have json like this
{
"result": "success",
"response_code": 200,
"message": "",
"collection": {
"<channel_id>": {
"<category_id>": {
"id_category": "<category_id>",
"name": "<category>",
"date_created": "<date_tagged>"
},
"<category_id>": {
"id_category": "<category_id>",
"name": "<category>",
"date_created": "<date_tagged>"
}
}
}
}
which channel_id and category_id is not a fixed name. How do I can deserialize it on C#?
Assuming everything else is pretty much fixed, you might try to model this along these lines:
public class MyJsonClass
{
public String Result { get; set; }
public int Response_Code { get; set; }
public String Message { get; set; }
public Dictionary<String, Dictionary<String, JsonCategoryDescription>>
Collection { get; set; }
}
public class JsonCategoryDescription
{
public String Id_Category { get; set; }
public String Name { get; set; }
public String Date_Created { get; set; }
}
Then you deserialize it as follows (System.Web.Script.Serialization namespace):
var result = new JavaScriptSerializer().Deserialize<MyJsonClass>(myJsonString);
and you can access specific fields, like so:
result.Collection[SOME_CHANNEL_ID][SOME_CATEGORY_ID].Name = "XXX";
If you use Dynamic instead of a static type you can have a variable schema of your JSON file. Here is a working console program:
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText("file.json");
dynamic obj = JObject.Parse(json);
Console.WriteLine(obj.collection.channel_id);
}
}