I want to parse JSON string in C# asp.net mVC3 but not getting idea of how to parse my json string.
my JSON String is like that:
{"dept":"HR","data":[{"height":5.5,"weight":55.5},{"height":5.4,"weight":59.5},{"height":5.3,"weight":67.7},{"height":5.1,"weight":45.5}]}
Code:
var allData = { dept: deptname, data: arr};
var allDataJson = JSON.stringify(allData);
$.ajax({
url: '<%=Url.Action("funx","Controller")%>',
data: { DJson: allDataJson },
async: false,
cache: false,
type: 'POST',
success: function (data) {
alert("success data: "+data);
}
});
public String funx(string DJson)
{
System.Diagnostics.Debug.WriteLine("Returned Json String:" + DJson);
// var yourObject = new JavaScriptSerializer().Deserialize(DJson);
return "successfull";
}
I am new to asp.net. I want to parse the string and save it in database.
Method 1:
Create two classes with the structure of your JSON string:
public class myobj
{
public string dept;
public IEnumerable<mydata>;
}
public class mydata
{
public int weight;
public int height;
}
and after that use this to parse it:
public static T FromJSON<T>(string str)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Deserialize<T>(str);
}
Like this:
myobj obj = MP3_SIOP_LT.Code.Helpers.JSONHelper.FromJSON<myobj>(#"{""dept"":""HR"",""data"":[{""height"":5.5,""weight"":55.5},{""height"":5.4,""weight"":59.5},{""height"":5.3,""weight"":67.7},{""height"":5.1,""weight"":45.5}]}");
The result:
Method 2:
If you don't want to have classes with your JSON structure, use the same method as above like this but in order to get a dynamic object:
dynamic obj = MP3_SIOP_LT.Code.Helpers.JSONHelper.FromJSON<dynamic>(#"{""dept"":""HR"",""data"":[{""height"":5.5,""weight"":55.5},{""height"":5.4,""weight"":59.5},{""height"":5.3,""weight"":67.7},{""height"":5.1,""weight"":45.5}]}");
The result:
First create a model for your json
public class Size
{
public double height { get; set; }
public double weight { get; set; }
}
public class MyData
{
public string dept { get; set; }
public List<Size> data { get; set; }
}
Now you can deserialize your json. With built-in DataContractJsonSerializer
var serializer = new DataContractJsonSerializer(typeof(MyData));
var data = (MyData)serializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
or With Json.Net
var data = JsonConvert.DeserializeObject<MyData>(json);
You can even go the dynamic way without creating any classes
dynamic dynObj = JsonConvert.DeserializeObject(json);
foreach(var item in dynObj.data)
{
Console.WriteLine("{0} {1}", item.height, item.weight);
}
You can use NewtonSoft Json.Net for parsing.
Try this
var json = "{\"dept\":\"HR\",\"data\":[{\"height\":5.5,\"weight\":55.5},{\"height\":5.4,\"weight\":59.5},{\"height\":5.3,\"weight\":67.7},{\"height\":5.1,\"weight\":45.5}]}";
var foo = JsonConvert.DeserializeObject<RootObject>(json);
// Check Values
// var department = foo.dept;
// foreach (var item in foo.data)
// {
// var height = item.height;
// var weight = item.weight;
// }
public class Datum
{
public double height { get; set; }
public double weight { get; set; }
}
public class RootObject
{
public string dept { get; set; }
public List<Datum> data { get; set; }
}
Nuget: Json.Net
Related
I am trying to parse manually a string in json. This is how my json look like
{{
"dbViews": [
{
"viewID": 0,
"viewColumns": [
{
"dbTitle": "ColNmid",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
},
{
"dbTitle": "ColNmdelete",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
}
]
}
],
"AddViewName": "test"
}}
This is how i am trying to read it.
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.id = obj.dbViews.viewID;
User.viewName = obj.AddViewName;
foreach (var item in obj.viewColumns)
{
if (obj.dbTitle == "ColNmid")
{
User.ColNmid = obj.viewTitle;
}
}
I can only read addViewName, i can't seem to access viewID or viewColumn.
Update:
after the comments I obviously miss the second array. Here my new code witch work
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.viewName = obj.AddViewName;
foreach (var view in obj.dbViews)
{
User.id = view.viewID;
foreach (var item in view.viewColumns)
{
if (item.dbTitle == "ColNmid")
{
User.ColNmid = item.viewTitle;
}
}
}
Your json in question is invalid (extra { and } at start and end). It seems that you are using Newtonsoft's Json.NET library. Usual approach is to create model corresponding to your json structure and deserialize it:
public class Root
{
[JsonProperty("dbViews")]
public List<DbView> DbViews { get; set; }
[JsonProperty("AddViewName")]
public string AddViewName { get; set; }
}
public class DbView
{
[JsonProperty("viewID")]
public long ViewId { get; set; }
[JsonProperty("viewColumns")]
public List<ViewColumn> ViewColumns { get; set; }
}
public class ViewColumn
{
[JsonProperty("dbTitle")]
public string DbTitle { get; set; }
[JsonProperty("viewTitle")]
public string ViewTitle { get; set; }
[JsonProperty("activated")]
public bool Activated { get; set; }
[JsonProperty("activatedLabel")]
public string ActivatedLabel { get; set; }
}
var result = JsonConvert.DeserializeObject<Root>();
You don't need to include all properties in your class, you can include only needed ones.
If you don't want to create custom models and want to loop through the JObject properties in your case you can do it for example like that:
var jObj = JObject.Parse(json);
foreach(var view in jObj["dbViews"]) // dbViews is an array
{
Console.WriteLine(view["viewID"]);
foreach (var viewColumn in view["viewColumns"]) // viewColumns is an array
{
Console.WriteLine(viewColumn["dbTitle"]);
}
}
I have this JSON string but are not sure how I will parse out the values that are inside:
has
has2
I do succeed to parse out the "id" correctly but are not sure how to access:
CORS
CORS2
CORS3
CORS4
I get the error:
'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.String[]' because the type requires a JSON array (e.g. [1,2,3])
I have pasted the JSON in the pastebin:
https://pastebin.com/iWgGV9VK
The code I have:
public void getInfo()
{
String JSONstring = "{ id: 'hello', name: 'Hello',has:{ CORS: false,CORS2: true},has2:{ CORS3: false,CORS4: true}}";
String id = ""; List<String> has = new List<String>(); List<String> has2 = new List<String>();
var deserializedTicker = JsonConvert.DeserializeObject<JsonInfo>(JSONstring);
id = deserializedTicker.id;
has = deserializedTicker.has.ToList();
has2 = deserializedTicker.has.ToList();
}
public class JsonInfo
{
public String id { get; set; }
public String[] has { get; set; }
public String[] has2 { get; set; }
}
I am trying with the dynamic approach using an object but gets an error here also:
''Newtonsoft.Json.Linq.JValue' does not contain a definition for 'id''
//responseBody holds the JSON string
dynamic stuff = JsonConvert.DeserializeObject(responseBody);
foreach (var info in stuff)
{
dynamic id = info.Value.id; //''Newtonsoft.Json.Linq.JValue' does not contain a definition for 'id''
dynamic has = info.Value.has;
dynamic has2 = info.Value.has2;
if (has != null && has2 != null)
{
dynamic cors = has.CORS;
if(cors != null)
{
MessageBox.Show(cors.ToString());
}
}
}
First off, let's correct your JSON:
{
"id": "hello",
"name": "Hello",
"has": {
"CORS": false,
"CORS2": true
},
"has2": {
"CORS3": false,
"CORS4": true
}
}
Now, the problem you are experiencing is because you are attempting to deserialize the value in "has" and "has2" as arrays. In the JSON, they are not arrays; they are objects. As such, you need to define new classes with the same properties so the JSON can be properly deserialized:
public class JsonInfo
{
public string id { get; set; }
public string name { get; set; }
public JsonHasInfo has { get; set; }
public JsonHas2Info has2 { get; set; }
}
public class JsonHasInfo
{
public bool CORS { get; set; }
public bool CORS2 { get; set; }
}
public class JsonHas2Info
{
public bool CORS3 { get; set; }
public bool CORS4 { get; set; }
}
Now you should be able to deserialize the (correct) JSON properly:
String JSONstring = "{ \"id\": \"hello\", \"name\": \"Hello\", \"has\": { \"CORS\": false, \"CORS2\": true }, \"has2\": { \"CORS3\": false, \"CORS4\": true } }\";"
var deserializedTicker = JsonConvert.DeserializeObject<JsonInfo>(JSONstring);
You json was incorrect, the key has contains a dict no list.
You need change your deserialize to dictionary or change your json.
Here you can see an example:
https://json-schema.org/understanding-json-schema/reference/array.html#array
In your JSON, has is an object, not an array. You should model your class to support an object containing the attributes CORS, CORS2, and so on, and so forth.
Edit: If you want to stick to has being an array, you should change your JSON to match what an array expects, which could be like: has: [ false, true ], and omit the CORS thing.
I am trying to deserialize JSON file and want to assign to object ScanResult. var text showing all the values but scanresult showing null some null values. https://gyazo.com/ff2ce386f845394c458a88d43a1f30d8
please suggest if I am missing something.
//MY jSon File SCAN Test 1-1543045410222.json 's code
{
"at": 1543045410222,
"i": 1000,
"s": {
"Sensor1": ["OFF"],
"Sensor2": ["OFF"],
"DataReady1": ["OFF"],
"DataReady2": ["OFF"],
"CV1": [5.0],
"CV2": [6.0]
}
}
//ViewModel Code is as below:
public void ResendScanResult()
{
var ScanActivities = scanActivityManager.GetAll();
foreach (var item in ScanActivities)
{
var scanName = item.ScanName;
var dir = _dataFilePath + scanName + "\\";
var jsonFileName = string.Format("{0}{1}-{2}.json", dir, scanName, item.ScanDateEpoch);
string fileName = Path.GetFileName(jsonFileName);
// ScanResult scanResult = new ScanResult();
var text = File.ReadAllText(jsonFileName);
//var scanResults = JsonConvert.DeserializeObject<ScanResult>(text);
Common.Model.ScanResult scanResult = JsonConvert.DeserializeObject<Common.Model.ScanResult>(text);
var Mvm = MonitorViewModel.Instance;
// TargetProvider target = Mvm.GetTargetProvider(scanResult);
// Mvm.PublishToServer(target, scanResult);
}
}
and my scanRescult class code is as below :
namespace ABX.Common.Model
{
public class ScanResult
{
public ScanResult()
{
At = DateTimeOffset.Now.ToUnixTimeMilliseconds();
Interval = 1;
}
public string Name { get; set; }
public long At { get; set; }
public long Interval { get; set; }
public JObject Values { get; set; }
public string FileName { get; set; }
public JObject ToJson()
{
JObject json = new JObject
{
{ "at", At },
{ "i", Interval },
{ "s", Values }
};
return json;
}
Either rename your class properties to match your JSON, rename your JSON to match your class properties, or implement a custom JsonConverter, where you can implement arbitrary mapping.
I am sending URL request and getting response in curl and then convert into a json...object inside object(contain numeric and dot(924.136028459)) like:
string arr1 =
"{
"success":1,
"results":[
{
"Markets":{
"924.136028459":{
"productType":"BOOK1",
"key":"SB_MARKET:924.136028459"
},
"924.136028500":{
"productType":"BOOK2",
"key":"SB_MARKET:924.136028459"
}
}
}
]
}";
I have created properties class ..but i am not understanding how can we access inside "924.136028500" attributes
public class Json
{
public System.Collections.ObjectModel.Collection<Arr> results { get; set; }
}
public class Arr
{
public sp Markets { get; set; }
}
public class sp
{
public string productType { get; set; }
public string key { get; set; }
}
and I am using deserialize code...
var serializer = new JavaScriptSerializer();
Json json = serializer.Deserialize<Json>(arr1);
With Cinchoo ETL - an open source library, you can load the Market object easily with few lines of code
string json = #"{
""success"":1,
""results"":[
{
""Markets"":{
""924.136028459"":{
""productType"":""BOOK1"",
""key"":""SB_MARKET:924.136028459""
},
""924.136028500"":{
""productType"":""BOOK2"",
""key"":""SB_MARKET:924.136028459""
}
}
}
]
}
";
foreach (var rec in ChoJSONReader<sp>.LoadText(json).WithJSONPath("$..Markets.*"))
Console.WriteLine($"ProductType: {rec.productType}, Key: {rec.key}");
Output:
ProductType: BOOK1, Key: SB_MARKET:924.136028459
ProductType: BOOK2, Key: SB_MARKET:924.136028459
Checkout CodeProject article for some additional help.
Disclaimer: I'm the author of this library.
How can I deserialize:
{
"data": [
{"ForecastID":8587961,"StatusForecast":"Done"},
{"ForecastID":8588095,"StatusForecast":"Done"},
{"ForecastID":8588136,"StatusForecast":"Done"},
{"ForecastID":8588142,"StatusForecast":"Pending"}
]
}
to
class RawData
{
public string data { get; set; }
}
So, I just want to have
[
{"ForecastID":8587961,"StatusForecast":"Done"},
{"ForecastID":8588095,"StatusForecast":"Done"},
{"ForecastID":8588136,"StatusForecast":"Done"},
{"ForecastID":8588142,"StatusForecast":"Pending"}
]
as value of property data of RawData's class instance.
Using Json.Net
var obj = (JObject)JsonConvert.DeserializeObject(json);
var newJson = obj["data"].ToString();
or using built-in JavaScriptSerializer
var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
var newjson = new JavaScriptSerializer().Serialize(dict["data"]);
It would have made far much more sense to deserialize this JSON structure to:
public class Forecast
{
public IEnumerable<ForecastData> Data { get; set; }
}
public class ForecastData
{
public int ForecastID { get; set; }
public string StatusForecast { get; set; }
}
which is pretty trivial with the JavaScriptSerializer class that's built into the framework:
string json = "your JSON data here";
IEnumerable<ForecastData> data = new JavaScriptSerializer()
.Deserialize<Forecast>(json)
.Data;
or if you don't want to define models you could do that:
dynamic result = new JavaScriptSerializer().DeserializeObject(json);
foreach (var item in result["data"])
{
Console.WriteLine("{0}: {1}", item["ForecastID"], item["StatusForecast"]);
}