I have tried numerous times and also tried to consult the documentation provided by Newtonsoft website but there doesn't seem to be any answer regarding my issue. I have also searched Google for no avail, wasted around 4 hours with no answer but just to continue without it.
My issue is that can't add a JObject into a JArray with a Key. I understand it seems rather simple task but whatever I tried ended up in an Exception being thrown out.
I am trying to write a simple file with the following layout:
{
"items" : [
"item 1" : { },
"item 2" : { },
]
}
// the actual layout that I have is
{
"items" : [
{ },
{ },
]
}
I can successfully add the first items key for JArray through jobj["items"] = jarray but I cant seem to use the same technique with JArray. I need to add items in JArray through JArray.Add() and it doesn't let me provide a key. I'm actually lost on this. Can someone please explain as how can I achieve the above layout? Thank you.
As #dbc mentioned, the format which you require is not valid. The nearest valid format you could achieve is as following.
{
"items":
{
"item 1":{},
"item 2":{}
}
}
You could achieve it using a Data structure containing a Dictionary. For Example
var data = new DataStructure{
items = new Dictionary<string,Item>()
{
["Item 1"] = new Item{},
["Item 2"] = new Item{}
}};
Where DataStructure and Item is defined as
public class DataStructure
{
public Dictionary<string,Item> items{get;set;}
}
public class Item
{
}
If you do not want to create concrete class, you can achieve the same using anonymous types
var data = new {items = new Dictionary<string,Item>()
{
["Item 1"] = new Item{},
["Item 2"] = new Item{}
}};
or, if you want to avoid creation of Item Class as well
var data = new {items = new Dictionary<string,object>()
{
["Item 1"] = new {},
["Item 2"] = new {}
}};
Output
{
"items": {
"Item 1": {},
"Item 2": {}
}
}
As it has been suggested in the comment, my desired layout is not a right one. As it appears json needs an anonymous object within the array to hold a keyed object.
So the layout should be:
{
"items" : [
{
"item1" : { }
},
.......
]
}
Related
I am new to C# and I am trying to create an object in a similar way that we create them in js:
var obj = {
'method' : 'connect',
'data' : {
'somekey' : 'data',
'somekey2' : 'data',
'somekey3' : 'data',
'somekey4' : 'data'
}};
Eventually this will be converted into JSON. So far I have tried using a dictionary like this:
connect.Method = "connect";
connect.Data = new Dictionary<string, object>();
connect.Data.Add("data", new Dictionary<string, object>()
{
{ "somekey", "data" },
{ "somekey2", "data" },
{ "somekey3", "data" },
{ "somekey4", "data" }
}
);
but doing that in the json output it looks like:
{
"Method":"connect",
"Data":{
"data":{
"somekey":"data",
"somekey2":"data",
"somekey3":"data",
"somekey4":"data"}
}
}
Which is problematic because the M in method shouldn't be capitalized (its that way because how I defined the class I am sure I can fix this one myself.
The main issue is the extra "Data" that is getting added into the JSON.
Does anyone have any ideas of a better way to do this, I am trying to avoid just using huge strings to convert into JSON.
In your C# code you create 2 dictionaries inside each other. That's why you get the extra levels in the structure.
You could eliminate one level by doing this
connect.Method = "connect";
connect.Data = new Dictionary<string, object>
{
{ "somekey", "data" },
{ "somekey2", "data" },
{ "somekey3", "data" },
{ "somekey4", "data" }
};
As for having lower case variable names, you can add the JsonProperty attribute to the fields. Here are the docs: https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm
I have a simple JSON example like this :
{
"items": {
"element": ["item 1","item 2"]
},
"name": "James"
}
and a JSON Schema like this :
{
'type': 'object',
'properties': {
'name': {'type':'string'},
'items': {
'type': 'object',
'properties':{
'element':{
'type':'array',
'items':[{'type':'string', 'type':'string'}]
}
}
}
},
'additionalProperties': false
}
Calling "IsValid()" method in JSON.NET using the given Schema and Data will return VALID.
Question :
How do I traverse and edit the elements inside JSON ?
My objective is to look-up values of node "element" in database and then replace it with a generalized value if they exists e.g "item 1" exists in database and will replaced with "general value A". However, "item 2" doesn't exist in database and should throw some kind of error message when IsValid() method is called.
Note that this is a desktop application using .NET 4.5 and JSON.NET library, and it will be used as a data-cleansing tool. I'm open to any kind of alternative libraries as long as they are compatible with .NET 4.5 though..
Not fully understand the part of your question with IsValid() issue, but if talk about traversing through json elements and editing, you can use 2 methods.
Install Newtonsoft.Json at first in Package-Manager in VS: Install-package newtonsoft.json.
Create class JsonItems, which describes your input JSON hierarchy
class JsonItems
{
public Items items;
public string name;
}
class Items
{
public List<string> elements { get; set; }
}
Now you can legally deserialize your json and edit result as any .net object.
string jsonItems = #"{
'items': {
'element': ['item 1','item 2']
},
'name': 'James'
}";
var result = JsonConvert.DeserializeObject<JsonItems>(jsonItems);
result.items = new Items
{
elements = new List<string> {"itemd 3", "item 4"}
};
2. The second way is more quick (in implementation), but less secuarble in runtime. With help of dynamic.
dynamic d = JObject.Parse(jsonItems);
d.items.element[1] = "item 3";
I have an ASP.NET MVC app. I am trying to hit an external web service from the controller in my app. Currently, I am hitting the web service like this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(GetServiceUrl());
dynamic data = System.Web.Helpers.Json.Decode(...)
}
The result from the web service can have three different schemas in JSON. They look like this;
schema 1
{
"request":"some info",
"value": [
{"id":1, name:"bill" },
{"id":2, name:"john" }
]
}
schema 2
{
"request":"some info",
"value": [
{ "orderId":"A12345", orderDate:"10-12-2014" },
{ "orderId":"B31234", orderDate:"11-01-2014" },
{ "orderId":"C36512", orderDate:"12-03-2014" },
]
}
schema 3
{
"request":"some info",
"value": [
{ "productId":"11-22-33", "name":"ball", "description":"a round thing" },
{ "productId":"3A-12-52", "name":"tire", "description":"keeps you moving" },
{ "productId":"7D-xy-23", "name":"plate", "description":"something to eat off of." },
]
}
I would like to avoid writing three separate classes if at all possible. I really only want to do two things: 1) count the number of objects in the value array. 2) Loop through the objects in the value array and print out some of the values via Razor.
Can I do these two things without creating 3 new classes? If so, how?
THank you!
Assuming you're using json.net, you can use JObject and JArray.
var json = #"{'value': [ { 'id' : 1}, { 'id' : 2 } ]}";
var jObject = JObject.Parse(json);
var values = (JArray) jObject["value"];
Console.WriteLine("Number of items: {0}", values.Count);
foreach (var value in values)
{
// do something with value.
}
If you're not using json.net, you could go with Robert Harvey's suggestion and use JavaScriptSerializer.
var jsonDict = serializer.Deserialize<IDictionary<string, object>>(json);
var array = (IEnumerable<object>) jsonDict["value"];
I have a C# class which contains a property of Dictionary
I have a web-page which contains a list of items i need to cast into this dictionary.
My web-site will send the list up to my C# MVC application as JSON and then JsonConvert.Deserialise the JSON into my Dictionary object.
JsonConvert.Deserialise is expecting JSON in the following format:
"MyVariableName":{
"Item 1":true,
"Item 2":true
}
I need to know how i can construct this object in JavaScript.
So far, i have tried this without luck:
var items = [];
var v = $('#Items :input');
$.each(v, function(key, val) {
items.push({
key: val.value,
value: val.checked
});
});
JSON.stringify(v, null, 2);
But this returns a json converted value of:
"MyVariableName": [
{
"key": "Item 1",
"value": true
},
{
"key": "Item 2",
"value": true
}]
Which in turn does not de-serialize to my dictionary.
Thanks
Don't make an array; make an object:
var items = {};
$('#Items :input').each(function(i, val) {
items[val.value] = val.checked;
});
You have to use javascript serialization
One more thing you have different value int key, value pair like string and Boolean type, so you have to use Dictionary type.
And JavaScriptSerializerobject you will get System.Web.Script.Serialization name space of System.Web.Extensions.dll, v4.0.30319 assembly.
var jSerializer = new JavaScriptSerializer();
var newList= jSerializer.Deserialize<Dictionary<string,object>>(newData);
I'm trying to generate JSON using C# and DataContractJsonSerializer in .Net 3.5. The problem is that I can't figure out how to build the structure correct for the result I need.
I've tried to reproduce PHP's associative arrays using both hashtables, list objects and arraylists but can't figure out how to generate my result in the best way using DataContractJsonSerializer without having to create my own recursive loop for building JSON.
The closest approach is using the a Dictionary < string, Dictionary < string, string>> aproach but the result is too big as I can't "name" the keys.
This is what I get:
[
{
"Key":"status",
"Value":[
{
"Key":"value",
"Value":"ok"
}
]
},
{
"Key":"1",
"Value":[
{
"Key":"name",
"Value":"Result1"
},
{
"Key":"details",
"Value":"Result 1 details"
}
]
},
{
"Key":"2",
"Value":[
{
"Key":"name",
"Value":"Result2"
},
{
"Key":"details",
"Value":"Result 2 details"
}
]
},
{
"Key":"caller",
"Value":[
{
"Key":"value",
"Value":"1135345"
}
]
}
]
This is what I want:
{
"status":"ok",
"response":[
{
"id":1,
"name":"Result1"
"details":"Result 1 details"
},
{
"id":2,
"name":"Result2"
"details":"Result 2 details"
},
{
"id":3,
"name":"Result3"
"details":"Result 3 details"
],
"caller":"1135345"
}
Does anybody have a clue how I can generate this piece of JSON using C# without having to load the entire Json.NET framework? I need this to be generated as fast as possible as this project aims to become an site search engine.
You should look at using the JavaScriptSerializer. It's part of the .NET framework (distributed in System.Web.Extensions). To get the result you want you can do this:
var results = new[]
{
new{id=1,name="Result 1"},
new{id=2,name="Result 2"},
new{id=3,name="Result 3"}
};
var js = new JavaScriptSerializer();
var result = js.Serialize(new
{
status = "ok",
response = results,
caller = 1135345
});
You can either use anonymous classes, or any existing ones. Works perfectly fine :)
The return value of this call would be:
{"status":"ok","response":[{"id":1,"name":"Result 1"},{"id":2,"name":"Result 2"},{"id":3,"name":"Result 3"}],"caller":1135345}
Using the JavaScriptSerializer rather than DataContractJsonSerializer on a Dictionary will remove the Key/Value json attributes and make them into a "keyed" array.
http://msdn.microsoft.com/en-us/library/bb412168.aspx
Have you attributed your classes with the [DataContract] and [DataMember] decorators?
http://msdn.microsoft.com/en-us/library/bb412179.aspx