I'm a little lost with serializing a JSON object, I'm trying to serialize the Item class into a JSON
class Item
{
public Dictionary<string, object> components = new Dictionary<string, object> { };
public string mixins { get; set; }
public string type { get; set; }
}
class Components
{
public Dictionary<string, object> unit_info = new Dictionary<string, object> { };
public Dictionary<object, object> generateUnitInfo()
{
unit_info.Add("bla", "blubb");
unit_info.Add("blubb", "bla");
return unit_info;
}
}
My JSON should look like this
{
"components": {
"unit_info" : {
"bla": "blubb",
"blubb": "bla",
},
}
}
Any hint would be helpful, thanks in advance
EDIT: thats the code that I have so far
Component c = new Component();
Item item = new Item();
item.type = CBItemType.SelectedItem.ToString();
item.mixins = "test mixins";
item.components.Add(c.unit_info, c.generateUnitInfo());
string json = JsonConvert.SerializeObject(item, Formatting.Indented);
and thats what I get
{
"mixins": "test mixins",
"type": "entity",
"components": {
"(Collection)": {
"bla": "blubb",
"blubb": "bla"
}
},
"entity_data": {}
}
The generateUnitInfo method adds 2 k/v pairs to the unit_info, I want instead of (Collection) unit_info
You can use anonymous objects (Json.Net)
var obj = new { components = new { unit_info = new { bla="blubb", blubb="bla" } } };
var json = JsonConvert.SerializeObject(obj);
Built-in JavaScriptSerializer would give the same result too
var json = new JavaScriptSerializer().Serialize(obj);
PS: If using dictionary is a must you can use it too
var obj = new Dictionary<string, object>()
{
{
"components", new Dictionary<string,object>()
{
{
"unit_info" , new Dictionary<string,object>()
{
{ "bla", "blubb" }, {"blubb", "bla" }
}
}
}
}
};
Both serializers will return your expected json.
Related
My response model class
public class MyModel
{
public Tuple<string, string> Data{ get; set; }
}
var data = new MyModel
{
Data = Tuple.Create("error", "12345");
};
which results in the following json response
{
"data": {
"item1": "error",
"item2": "12345"
}
}
What I want is to create a response as follows
"data" : [{ "error" : "12345" }]
These item1 and item2 are of course dynamic data and it can be anything of type string. I'm saying this because I cannot simply decorate the properties with JsonProperty attribute.
You need either to implement custom serializer for your tuple or change your model to represent the desired structure. If you don't want to create some specific types for your inner data you can leverage Dictionary serialization convention:
public class MyModel
{
public Dictionary<string, string>[] Data{ get; set; }
}
And creation:
var data = new MyModel
{
Data = new[]
{
new Dictionary<string, string> { { "error", "message" } }
}
};
Or make your field into array of objects and create anonymous ones:
public class MyModel
{
public object[] Data{ get; set; }
}
var data = new MyModel
{
Data = new[]
{
new { error = "message" }
}
}
I am having a string in the following format. I want to assign each JSON within the projects to a separate JObject. When I am trying to parse it and assign accordingly, I am unable to achieve it. How can I parse it?
{
"projects": [
{
"sno": "1",
"project_name": "Abs",
"project_Status": "Live"
},
{
"sno": "2",
"project_name": "Cgi",
"project_Status": "Live"
}
]
}
I have tried the following code;
using (StreamReader streamReader = new StreamReader(Path.Combine(Path.GetTempPath(), "sample.json")))
using (JsonTextReader reader = new JsonTextReader(streamReader))
{
var serializer = new JsonSerializer();
while (reader.Read())
{
if (reader.TokenType == JsonToken.StartObject)
{
JObject jsonPayload = JObject.Load(reader);
jsonProfile = jsonPayload.ToString();
JObject json = JObject.Parse(jsonProfile);
}
}
}
you can use DeserializeAnonymousType as a simpler solution to parse json.
var definition = new
{
projects = new[]{
new {
sno="1",
project_name= "Abs",
project_Status= "Live"
}
}
};
string json1 = #" {
'projects': [
{
'sno': '1',
'project_name': 'Abs',
'project_Status': 'Live'
},
{
'sno': '2',
'project_name': 'Cgi',
'project_Status': 'Live'
}
]
}";
var projects = JsonConvert.DeserializeAnonymousType(json1, definition);
but if you do want to use strong type, you'd better to use JsonProperty
public class Project
{
[JsonProperty("sno")]
public string Sno { get; set; }
[JsonProperty("project_name")]
public string ProjectName { get; set; }
[JsonProperty("project_Status")]
public string ProjectStatus { get; set; }
}
public class JsonModel
{
[JsonProperty("Projects")]
public List<Project> projects { get; set; }
}
JsonConvert.DeserializeObject<JsonModel>(json_Data);
Pretty silly question to ask. but could not figure it out .
In a C# MVC Controller action , I need to model a Json Array for testing purposes.
But this shows me compilation errors instead of being a valid Json:
var result = {
"controllerId": "controller1",
"controllerName": "ControllerOne"
};
But this is perfectly valid :
var scheduleResult = new[]
{
new { scheduleId = "schedule1",scheduleName = "scheduleOne"},
new { scheduleId = "schedule2",scheduleName = "scheduleTwo"}
};
Why so ?
Also how to write a nested Json array :
I tried :
var scheduleResult = new[]
{
new { scheduleId = "schedule1",scheduleName = "scheduleOne",new[]{ new {doorId="Door1",doorName="DoorOne"}, new { doorId = "Door2", doorName = "DoorTwo" } } },
new { scheduleId = "schedule2",scheduleName = "scheduleTwo"}
};
But it shows errors in syntax. What to do ?
I Need to have nested array within each element of that array .
Thanks in advance.
Well, C# does not support the way you wrote. You can't just type in JSON in C# and expect it to work unfortunately. You can try like that with anonymous type:
var result = new
{
controllerId = "controller1",
controllerName = "ControllerOne",
myArray = new []
{
"a",
"b"
}
};
This is converted to JSON no problem if you return it as a result of API call.
The nested arrays you are talking about don't work because you need to give them a name, you can't have array property without a name. See example above.
Why don't you use Dictionary<TKey, TValue> with Newtonsoft.Json?
Simple json:
IDictionary<string, string> obj = new Dictionary<string, string>();
obj.Add("controllerId", "controller1");
obj.Add("controllerName", "ControllerOne");
// {"controllerId":"controller1","controllerName":"ControllerOne"}
string json = JsonConvert.SerializeObject(obj);
Nested json:
IList<string> obj = new List<string>();
IDictionary<string, string> first = new Dictionary<string, string>();
first.Add("scheduleId ", "schedule1");
first.Add("scheduleName", "scheduleOne");
IDictionary<string, string> second = new Dictionary<string, string>();
second.Add("scheduleId ", "schedule2");
second.Add("scheduleName", "scheduleTwo");
string first_json = JsonConvert.SerializeObject(first);
string second_json = JsonConvert.SerializeObject(second);
obj.Add(first_json);
obj.Add(second_json);
// ["{\"scheduleId \":\"schedule1\",\"scheduleName\":\"scheduleOne\"}","{\"scheduleId \":\"schedule2\",\"scheduleName\":\"scheduleTwo\"}"]
string json = JsonConvert.SerializeObject(obj);
Here first of all we should create model class with the same pattern of our return type
public class ScheduleModel
{
public List<Schedule> ScheduleList { get; set; }
}
public class Schedule
{
public int ScheduleId { get; set; }
public string ScheduleName { get; set; }
public List<Door> DoorList { get; set; }
}
public class Door
{
public int DoorId { get; set; }
public string DoorName { get; set; }
}
Now at the controller Action create the test data
List<Door> doorList = new List<Door>();
doorList.Add(new Door{DoorId = "Door1",DoorName = "DoorOne"});
doorList.Add(new Door{DoorId = "Door2",DoorName = "DoorTwo"});
List<Schedule> scheduleList = new List<Schedule>();
scheduleList.Add(new Schedule{
ScheduleId = "schedule1",
ScheduleName = "scheduleOne",
DoorList = doorList
});
scheduleList.Add(new Schedule
{
ScheduleId = "schedule2",
ScheduleName = "scheduleTwo",
});
return Json(scheduleList, JsonRequestBehavior.AllowGet);
If this answer benefits you please mark as an answer.
I am trying to serialize some JSON for an API call:
string f5Name = "MyBigIpName";
string poolName = "myPoolName";
string postJson2 = JsonConvert.SerializeObject(
new
{
f5 = new {
f5Name = new {
poolName = memberState
},
}
}
);
This results in the following JSON:
{
"f5": {
"f5Name": {
"poolName": {
"member": {
"address": "10.0.0.0",
"port": 80
},
"session_state": "STATE_DISABLED"
}
}
}
}
However, what I am really looking to do is produce this JSON:
{
"f5": {
"MyBigIpName": {
"myPoolName": {
"member": {
"address": "10.0.0.0",
"port": 80
},
"session_state": "STATE_DISABLED"
}
}
}
}
Is there any way to have the f5Name and poolName property names be dynamic so that I can produce the above JSON? I am using Newtonsoft.JSON (JSON.NET)
I'm not sure if you could do something with a dynamic type or not, but you for sure can do something with Dictionaries:
var obj = new
{
f5 = new Dictionary<string, object>
{
{
f5Name, new Dictionary<string, object> {
{poolName, memberState}
}
}
}
}
string postJson2 = JsonConvert.SerializeObject(obj);
For what you are intending, you'd need to resolve your names in a contract resolver. Something like:
private class MyContractResolver : DefaultContractResolver
{
private Dictionary<string,string> _translate;
public MyContractResolver(Dictionary<string, string> translate)
{
_translate = translate;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
string newPropertyName;
if(_translate.TryGetValue(property.PropertyName, out newPropertyName))
property.PropertyName = newPropertyName;
return property;
}
}
And then:
string f5Name = "MyBigIpName";
string poolName = "MyPoolName";
var _translator = new Dictionary<string, string>()
{
{ "f5Name", f5Name },
{ "poolName", poolName },
};
string postJson2 = JsonConvert.SerializeObject(
new
{
f5 = new {
f5Name = new {
poolName = memberState
},
},
new JsonSerializerSettings { ContractResolver = new MyContractResolver(_translator) });
If you use C# 6, you could benefit from nameof and/or make it cleaner with a dictionary intializer:
var _translator = new Dictionary<string, string>()
{
[nameof(f5Name)] = f5Name ,
[nameof(poolName)] = poolName ,
};
The dictionary creation process could be automated easily too :-)
I have to read a JSON stream (which I have no control over), which is in the form:
{"files":
{
"/some_file_path.ext": {"size":"1000", "data":"xxx", "data2":"yyy"},
"/other_file_path.ext": {"size":"2000", "data":"xxx", "data2":"yyy"},
"/another_file_path.ext": {"size":"3000", "data":"xxx", "data2":"yyy"},
}
}
So, I have an object named files, which has a number of properties, which have 1) different names every time, 2) different number of them every time, and 3) names with characters which can't be used in C# properties.
How do I deserialize this?
I'm putting this into a Portable Library, so I can't use the JavaScriptSerializer, in System.Web.Script.Serialization, and I'm not sure about JSON.NET. I was hoping to use the standard DataContractJsonSerializer.
UPDATE: I've changed the sample data to be closer to the actual data, and corrected the JSON syntax in the area the wasn't important. (Still simplified quite a bit, but the other parts are fairly standard)
You can model your "files" object as a Dictionary keyed by the JSON property name:
public class RootObject
{
public Dictionary<string, PathData> files { get; set; }
}
public class PathData
{
public int size { get; set; }
public string data { get; set; }
public string data2 { get; set; }
}
Then, only if you are using .Net 4.5 or later, you can deserialize using DataContractJsonSerializer, but you must first set DataContractJsonSerializerSettings.UseSimpleDictionaryFormat = true:
var settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true };
var root = DataContractJsonSerializerHelper.GetObject<RootObject>(jsonString, settings);
With the helper method:
public static class DataContractJsonSerializerHelper
{
public static T GetObject<T>(string json, DataContractJsonSerializer serializer = null)
{
using (var stream = GenerateStreamFromString(json))
{
var obj = (serializer ?? new DataContractJsonSerializer(typeof(T))).ReadObject(stream);
return (T)obj;
}
}
public static T GetObject<T>(string json, DataContractJsonSerializerSettings settings)
{
return GetObject<T>(json, new DataContractJsonSerializer(typeof(T), settings));
}
private static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.Unicode.GetBytes(value ?? ""));
}
}
Alternatively, you can install Json.NET and do:
var root = JsonConvert.DeserializeObject<RootObject>(jsonString);
Json.NET automatically serializes dictionaries to JSON objects without needing to change settings.
We need to first convert this Invalid JSON to a Valid JSON. So a Valid JSON should look like this
{
"files":
{
"FilePath" : "C:\\some\\file\\path",
"FileData" : {
"size": 1000,
"data": "xxx",
"data2": "yyy"
},
"FilePath" :"C:\\other\\file\\path",
"FileData" : {
"size": 2000,
"data": "xxx",
"data2": "yyy"
},
"FilePath" :"C:\\another\\file\\path",
"FileData" : {
"size": 3000,
"data": "xxx",
"data2": "yyy"
}
}
}
To make it a valid JSON we might use some string functions to make it looks like above. Such as
MyJSON = MyJSON.Replace("\\", "\\\\");
MyJSON = MyJSON.Replace("files", "\"files\"");
MyJSON = MyJSON.Replace("data:", "\"data:\"");
MyJSON = MyJSON.Replace("data2", "\"data2\"");
MyJSON = MyJSON.Replace(": {size", ",\"FileData\" : {\"size\"");
MyJSON = MyJSON.Replace("C:", "\"FilePath\" :\"C:");
Than we can create a class like below to read the
public class FileData
{
public int size { get; set; }
public string data { get; set; }
public string data2 { get; set; }
}
public class Files
{
public string FilePath { get; set; }
public FileData FileData { get; set; }
}
public class RootObject
{
public Files files { get; set; }
}
Assuming you have a valid JSON you could use JavaScriptSerializer to return a list of objects
string json = "{}"
var serializer = new JavaScriptSerializer();
var deserializedValues = (Dictionary<string, object>)serializer.Deserialize(json, typeof(object));
Alternatively you could specify Dictionary<string, List<string>> as the type argument
strign json = "{}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
var deserializedValues = serializer.Deserialize<Dictionary<string, List<string>>>(json);
foreach (KeyValuePair<string, List<string>> kvp in deserializedValues)
{
Console.WriteLine(kvp.Key + ": " + string.Join(",", kvp.Value));
}