I am trying to get name from first item in deserialized JSON object.
When I debugged code, I found that jsonObject is converted to dictionary.
How can I get first item value from jsonObject.
var myJson= [
{name:'abc',city:'dallas'},
{name:'def',city:'redmond'},
{name:'ghi',city:'bellevue'},
]
JavaScriptSerializer jss = new JavaScriptSerializer();
var jsonObject = jss.Deserialize<dynamic>(myJson);
NameInFirstItem = jsonObject[0].name;
Create a class to hold your resulting object:
public class MyJsonResult
{
public string name { set; get; }
public string result { set; get; }
}
static void Main(string[] args)
{
string myJson = "[{ name: 'abc',city: 'dallas'},{ name: 'def',city: 'redmond'},{ name: 'ghi',city: 'bellevue'}]";
JavaScriptSerializer jss = new JavaScriptSerializer();
List<MyJsonResult> jsonResultList = jss.Deserialize<List<MyJsonResult>>(myJson);
var NameInFirstItem = jsonResultList.FirstOrDefault().name;
}
Or if you insist on using dynamic:
static void Main(string[] args)
{
string myJson = "[{ name: 'abc',city: 'dallas'},{ name: 'def',city: 'redmond'},{ name: 'ghi',city: 'bellevue'}]";
JavaScriptSerializer jss = new JavaScriptSerializer();
var jsonResultList = jss.Deserialize<List<dynamic>>(myJson);
// get first value by key from the dictionary
var NameInFirstItem = jsonResultList.FirstOrDefault()["name"];
}
I prefer the first method. If you add a third property to your json, you might get confused with type of the generated object, which is probably a list of key-value pairs for each object in your list.
Try this:
var NameInFirstItem = jsonObject[0]["name"];
You can deserialize the json with
public class Details
{
public string name { get; set; }
public string city { get; set; }
}
var res = JsonConvert.DeserializeObject<Details[]>(json);
var name = res[0].name;
Related
string sampleString = "[{\"id\":\"1\",\"status\":302},{\"id\":\"2\",\"status\":302},{\"id\":\"3\",\"status\":302},{\"id\":\"4\",\"status\":302}]";
JArray json = JArray.Parse(sampleString );
TempValue t;
foreach(JObject obj in json)
{
t = new TempValue {
id =//id of json,
status=//state of json
};
}
i want to access value of json anonymous objec to assign to t object.
It is always good to work with a typed object to avoid typing mistakes. In this case create a class with the structure of the json string like so:
public class StatusObj
{
public string id { get; set; }
public int status { get; set; }
}
The deserialize the json string to list of your class like so:
List<StatusObj> obj = JsonConvert.DeserializeObject<List<StatusObj>>(sampleString);
And then you can loop through the list like so:
foreach (var item in obj)
{
var id = item.id;
var status = item.status;
}
The whole code look like this:
class Program
{
static void Main(string[] args)
{
string sampleString = "[{\"id\":\"1\",\"status\":302},{\"id\":\"2\",\"status\":302},{\"id\":\"3\",\"status\":302},{\"id\":\"4\",\"status\":302}]";
List<StatusObj> obj = JsonConvert.DeserializeObject<List<StatusObj>>(sampleString);
foreach (var item in obj)
{
var id = item.id;
var status = item.status;
}
}
}
public class StatusObj
{
public string id { get; set; }
public int status { get; set; }
}
NB. Newtonsoft.Json package needed to be installed. You can also convert any json to class here
By the indexer
foreach(JObject obj in json)
{
t = new TempValue {
id = obj["id"].ToString() ,
...
};
Object.Item Property (String)
Gets or sets the JToken with the specified property name.
How could I produce this JSON:
{"{}":""}
From this code:
JsonConvert.SerializeObject(new
{
brackets = ""
})
brackets should be replaced by {}
"{}" is a string, just like any other string, so you can use it as a key like you usually do.
There are two ways to achieve this.
Use a dictionary of string-to-string with custom name:
var dict = new Dictionary<string, string>
{
["{}"] = ""
};
string result = JsonConvert.SerializeObject(dict);
Use a class with custom property name:
public class MyClass
{
[JsonProperty(PropertyName = "{}")]
public string Brackets { get; set; }
}
// Usage:
var obj = new MyClass { Brackets = "" };
string result = JsonConvert.SerializeObject(obj);
Create a class that sets the property name using JsonProperty:
public class Foo
{
[JsonProperty("{}")]
public string Value { get; set; }
}
And deserialise like this:
var json = JsonConvert.SerializeObject(new Foo { Value = "" } );
I am trying to convert my json data to c sharp understandable format so that I can use JsonConvert.SerializeObject to convert that data to JSON format and send it over HTTP protocol. My json data is as follows:
{
"m2m:ae":
{
"api": "ADN_AE_ATCARD06",
"rr": "true",
"lbl": ["AT06"],
"rn": " adn-ae_AT06"
}
}
I tried to write it in c sharp understandable format but was able to do this:
var obj = new
{
m2m = new
{
api = "ADN_AE45",
rr = "true",
lbl = new[] { "ad" },
rn = "adfrt"
}
};
var result = JsonConvert.SerializeObject(obj, Formatting.Indented);
my issue is how to include m2m:ae into my c-sharp code. I am new to json, I am able to convert only if parent object has no value but if it has value I am not able to. please help.
I was incorrect in my comment. While "m2m:ae" is not a valid name for a C# property is valid JSON. This can be accomplished by tagging the class property with JsonProperty.
Define your class like this
public class TestJson
{
[JsonProperty("m2m:ae")]
public Class2 Class2Instance { get; set; }
}
public class Class2
{
public string Api { get; set; }
public string Rr { get; set; }
public string[] Lbl { get; set; }
public string Rn { get; set; }
}
and then populate your class like this
_sut = new TestJson
{
Class2Instance = new Class2 {Api = "ADN_AE45", Rr = "true", Lbl = new[] {"ad"}, Rn = "adfrt"}
};
and serialize
_result = JsonConvert.SerializeObject(_sut, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
The resulting serialized object looks like
{
"m2m:ae": {
"api": "ADN_AE45",
"rr": "true",
"lbl": ["ad"],
"rn": "adfrt"
}
}
and deserialization is the reverse
var test = JsonConvert.DeserializeObject<TestJson>(_result, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Did you write the Json in a text file?
If yeah so fileTxt is what is written on the file(as json)
String fileTxt = File.ReadAllText(Give a path for a file); //read from file
Jobject Json = Jobject.Parse(fileTxt); //convert the string to Json
Console.WriteLine($"rr: {Json["rr"]} "); // get the rr from json and print it
Other than class method mentioned by Fran one can use the Dictionary method to create key value pair and newtonsoft.json library to convert to json.
var sub= Dictionary<string,string>
{{"abc","xyz"}
};
var main = Dictionary<string,object>
{{"wer:asd",sub}
};
string str= JsonConvert.SerializeObject(main);
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));
}
[{
"channel_id":299,
"requests":[{
"order_id":3975,
"action":"REQUEST_LABELS"
}]
}]
How to create the above request in c# the requests can be multiple.
I am new to c# i tried the below:
Dictionary<long, List<object>> requestObject = new Dictionary<long, List<object>>();
List<object> listrequestObjects = new List<object>();
Request requestOb = new Request();
requestOb.order_id = 2372;
requestOb.action = "REQUEST_LABELS";
listrequestObjects.Add(requestOb);
requestObject.Add(2352635, listrequestObjects);
string requesttest = JsonConvert.SerializeObject(requestObject);
But getting a weird request. Please help.
The structure should look like :
public class Request
{
public int order_id { get; set; }
public string action { get; set; }
}
public class RootObject
{
public int channel_id { get; set; }
public List<Request> requests { get; set; }
}
You need to declare the root object also:
[Serializable]
public class Root {
public int channel_id;
public Request[] requests;
}
Then assign the value and serialize it:
var root = new Root();
root.channel_id = 299;
root.requests = listrequestObjects.ToArray();
string requesttest = JsonConvert.SerializeObject(root);
You can use Newtonsoft.Json.
try this
private JArray GetResponse()
{
var main_array = new JArray();
var channel_id = new JObject();
channel_id.Add("channel_id",299);
var request = new JArray();
var order_id = new JObject();
order_id.Add("order_id",3975);
var action = new JObject();
action.Add("action","REQUEST_LABELS");
request.Add(order_id);
request.Add(action);
main_array.Add(channel_id);
main_array.Add(request);
return main_array;
}
Please try the JavaScriptSerializer class available in namespace
using System.Web.Script.Serialization
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(requestObject);
The requestObject list is your custom class with all necessary properties.
Thanks