How can I parse JSON to a C# object? - c#

I have JSON data that I need to access from C#. The chapters element looks like this:
"chapters": [
[
2,
1416420134.0,
"2",
"546cdb2645b9efbff4582d51"
],
[
1,
1411055241.0,
null,
"541afe8945b9ef69885d3d74"
],
[
0,
1414210972.0,
"0",
"544b259c45b9efb061521235"
]
]
Here are my C# classes that are meant to contain that data:
public class test
{
public string[] chapters { get; set; }
}
public class TChapter
{
public test[] aa { get; set; }
}
How can I parse the JSON to C# objects?

Using Newtonsoft JSON you will want to do something like the following
using System;
using Newtonsoft.Json;
namespace JsonDeserializationTest
{
class Program
{
static void Main(string[] args)
{
var chaptersAsJson = "[" +
" [" +
" 2," +
" 1416420134.0," +
" \"2\"," +
" \"546cdb2645b9efbff4582d51\"" +
" ], " +
" [" +
" 1," +
" 1411055241.0," +
" null," +
" \"541afe8945b9ef69885d3d74\"" +
" ], " +
" [" +
" 0," +
" 1414210972.0," +
" \"0\"," +
" \"544b259c45b9efb061521235\"" +
" ]" +
"]";
var chaptersAsTwoDObjectArray = JsonConvert.DeserializeObject<object[][]>(chaptersAsJson);
// Use the chapters array
foreach (object[] chapter in chaptersAsTwoDObjectArray)
{
// what do you want to do with the object array?
Console.WriteLine(String.Join(", ", chapter));
}
Console.WriteLine("Finished.");
}
}
}
Note that your classes don't line up with your JSON.

Related

Visual Studio Code Snippet Scoped and Accessible to files in .vscode folder

I am trying to define a Global Snippet that is scoped (so it won't pop up in every file). However, when I try to scope it to json I cannot use it in for example .vscode/tasks.json.
Any suggestions?
Contents of: dotnetTasks.code-snippets
{
"dotnetTasks": {
"scope": "json",
"prefix": "dotnetTasks",
"body": [
" \"tasks\": [",
" {",
" \"label\": \"build\",",
" \"command\": \"/usr/local/bin/dotnet\",",
" \"type\": \"process\",",
" \"args\": [",
" \"build\",",
" \"\\${workspaceFolder}/src/${ProjectName}/${ProjectName}.csproj\",",
" \"/property:GenerateFullPaths=true\",",
" \"/consoleloggerparameters:NoSummary\"",
" ],",
" \"problemMatcher\": \"\\$msCompile\"",
" },",
" {",
" \"label\": \"publish\",",
" \"command\": \"/usr/local/bin/dotnet\",",
" \"type\": \"process\",",
" \"args\": [",
" \"publish\",",
" \"\\${workspaceFolder}/src/${ProjectName}/${ProjectName}.csproj\",",
" \"/property:GenerateFullPaths=true\",",
" \"/consoleloggerparameters:NoSummary\"",
" ],",
" \"problemMatcher\": \"\\$msCompile\"",
" },",
" {",
" \"label\": \"watch\",",
" \"command\": \"/usr/local/bin/dotnet\",",
" \"type\": \"process\",",
" \"args\": [",
" \"watch\",",
" \"run\",",
" \"--project\",",
" \"\\${workspaceFolder}/src/${ProjectName}/${ProjectName}.csproj\"",
" ],",
" \"problemMatcher\": \"\\$msCompile\"",
" }",
" ]"
],
"description": ".NET Core Tasks"
}
}

C# JSON decentralization for OCR Response

I'm using OCR API to capture text in an image. I want to deserialize the JSON response and extract each word from each line. No words are showing up when I run JsonConvert.DeserializeObject
Any help is appreciated!
Here's the response:
{
"language": "en",
"textAngle": -2.0000000000000338,
"orientation": "Up",
"regions": [
{
"boundingBox": "462,379,497,258",
"lines": [
{
"boundingBox": "462,379,497,74",
"words": [
{
"boundingBox": "462,379,41,73",
"text": "A"
},
{
"boundingBox": "523,379,153,73",
"text": "GOAL"
},
{
"boundingBox": "694,379,265,74",
"text": "WITHOUT"
}
]
},
{
"boundingBox": "565,471,289,74",
"words": [
{
"boundingBox": "565,471,41,73",
"text": "A"
},
{
"boundingBox": "626,471,150,73",
"text": "PLAN"
},
{
"boundingBox": "801,472,53,73",
"text": "IS"
}
]
},
{
"boundingBox": "519,563,375,74",
"words": [
{
"boundingBox": "519,563,149,74",
"text": "JUST"
},
{
"boundingBox": "683,564,41,72",
"text": "A"
},
{
"boundingBox": "741,564,153,73",
"text": "WISH"
}
]
}
]
}
]
}
There is a NuGet package already available for the Microsoft Azure OCR :
Install-Package Microsoft.Azure.CognitiveServices.Vision.ComputerVision
You can then include the OcrResult model class provided by the package:
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
Deserialize the JSON response to the model type and extract the text in each OcrLine object.
OcrResult ocrResult = JsonConvert.DeserializeObject<OcrResult>(JSONResult);
StringBuilder sb = new StringBuilder();
if (!ocrResult.Language.Equals("unk"))
{
foreach (OcrLine ocrLine in ocrResult.Regions[0].Lines)
{
foreach (OcrWord ocrWord in ocrLine.Words)
{
sb.Append(ocrWord.Text);
sb.Append(' ');
}
sb.AppendLine();
}
}
The example looks like
using System;
using Newtonsoft.Json;
namespace Rextester
{
public class Rootobject
{
public string language { get; set; }
public float textAngle { get; set; }
public string orientation { get; set; }
public Region[] regions { get; set; }
}
public class Region
{
public string boundingBox { get; set; }
public Line[] lines { get; set; }
}
public class Line
{
public string boundingBox { get; set; }
public Word[] words { get; set; }
}
public class Word
{
public string boundingBox { get; set; }
public string text { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
string val = "{\n" +
" \"language\": \"en\",\n" +
" \"textAngle\": -2.0000000000000338,\n" +
" \"orientation\": \"Up\",\n" +
" \"regions\": [\n" +
" {\n" +
" \"boundingBox\": \"462,379,497,258\",\n" +
" \"lines\": [\n" +
" {\n" +
" \"boundingBox\": \"462,379,497,74\",\n" +
" \"words\": [\n" +
" {\n" +
" \"boundingBox\": \"462,379,41,73\",\n" +
" \"text\": \"A\"\n" +
" },\n" +
" {\n" +
" \"boundingBox\": \"523,379,153,73\",\n" +
" \"text\": \"GOAL\"\n" +
" },\n" +
" {\n" +
" \"boundingBox\": \"694,379,265,74\",\n" +
" \"text\": \"WITHOUT\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"boundingBox\": \"565,471,289,74\",\n" +
" \"words\": [\n" +
" {\n" +
" \"boundingBox\": \"565,471,41,73\",\n" +
" \"text\": \"A\"\n" +
" },\n" +
" {\n" +
" \"boundingBox\": \"626,471,150,73\",\n" +
" \"text\": \"PLAN\"\n" +
" },\n" +
" {\n" +
" \"boundingBox\": \"801,472,53,73\",\n" +
" \"text\": \"IS\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"boundingBox\": \"519,563,375,74\",\n" +
" \"words\": [\n" +
" {\n" +
" \"boundingBox\": \"519,563,149,74\",\n" +
" \"text\": \"JUST\"\n" +
" },\n" +
" {\n" +
" \"boundingBox\": \"683,564,41,72\",\n" +
" \"text\": \"A\"\n" +
" },\n" +
" {\n" +
" \"boundingBox\": \"741,564,153,73\",\n" +
" \"text\": \"WISH\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
Rootobject r = JsonConvert.DeserializeObject<Rootobject>(val);
}
}
}
This is posted at Rextester

Convert Json to explicit new object, List initialization c#

Hi I am wondering if there is a way to convert a json object to explicit new object/List object for instance :
Convert this :
{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
into this c# code text:
new className() {
Name = "John",
Age = 30,
Cars = new List (){"Ford", "BMW", "Fiat" }
};
What I want to do is create the equivalent of a json code in to c# code.
You can use the JObject from Newtonsoft library
This is an example from the library
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
Console.WriteLine(o.ToString());
Output
{
"CPU": "Intel",
"Drives": [
"DVD read/writer",
"500 gigabyte hard drive"
]
}
Or you can use jsonutils to create a C# equivalence class
And then use Newtonsoft to parse the Json object
MyObject obj = JsonConvert.DeserializeObject<MyObject>(jsonContent);
You can use online services like https://www.jsonutils.com/
or
function Convert(jsonStr, classNr) {
var i = classNr == undefined ? 0 : classNr;
var str = "";
var json = JSON.parse(jsonStr);
for (var prop in json) {
if (typeof(json[prop]) === "number") {
if (json[prop] === +json[prop] && json[prop] !== (json[prop] | 0)) {
str += prop + " = " + json[prop] + "M, ";
} else {
str += prop + " = " + json[prop] + ", ";
}
} else if (typeof(json[prop]) === "boolean") {
str += prop + " = " + json[prop] + ", ";
} else if (typeof(json[prop]) === "string") {
str += prop + ' = "' + json[prop] + '", ';
} else if (json[prop] == null || json[prop] == undefined) {
str += prop + ' = null, ';
} else if (typeof(json[prop]) === "object") {
str += prop + " = " + Convert(JSON.stringify(json[prop]), i++) + ", ";
}
}
if (str.endsWith(', ')) {
str = str.substring(0, str.length - 2);
}
return "new Class" + i + "{ " + str + " }";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="tin" cols="100" rows="6">
{"A":12}
</textarea>
<input type="button" value="Just do it!" onclick="$('#result').text(Convert($('#tin').val()));" />
<div id="result"></div>
from https://stackoverflow.com/a/34590681/1932159

How to convert a struct xaml grid wpf to json array

I am using a xaml wpf grid. I want to convert struct the grid to json. Do you have any ideas on how?
Please see this example:
<GridBinding>
<Grid ID="grd1" ES="9" KFN="" PFN="" GN="گرید 1">
<Column ID="ID" SystemId="517" TableId="3082" FieldId="1" Properties="Header=ID,Visible=True,VisibleIndex=4,GroupIndex=-1,ReadOnly=True,SortIndex=1,SortOrder=Descending,Mask=0,Width=ناعدد," IsCondition="False" IsForce="False" VS="True" ISFormulla="False" VF="1" ReadOnly="True" />
<Column ID="Name" SystemId="517" TableId="3082" FieldId="2" Properties="Header=Name,Visible=True,VisibleIndex=1,GroupIndex=-1,ReadOnly=False,SortIndex=2,SortOrder=Ascending,Mask=0,Width=ناعدد," IsCondition="False" IsForce="False" VS="True" ISFormulla="False" VF="2" ReadOnly="False" />
<Column ID="Family" SystemId="517" TableId="3082" FieldId="3" Properties="Header=Family,Visible=True,VisibleIndex=2,GroupIndex=-1,ReadOnly=False,SortIndex=-1,SortOrder=None,Mask=1,Width=ناعدد," IsCondition="False" IsForce="False" VS="True" ISFormulla="False" VF="3" ReadOnly="False" />
<Column ID="Avg" SystemId="517" TableId="3082" FieldId="10" Properties="Header=Avg,Visible=True,VisibleIndex=3,GroupIndex=-1,ReadOnly=False,SortIndex=-1,SortOrder=None,Mask=0,Width=ناعدد," IsCondition="False" IsForce="False" VS="True" ISFormulla="False" VF="4" ReadOnly="False" />
<Column ID="ردیف" SystemId="0" TableId="0" FieldId="-1" Properties="Header=ردیف,Visible=True,VisibleIndex=0,GroupIndex=-1,ReadOnly=False,SortIndex=-1,SortOrder=None,Mask=0,Fixed=Left,Width=ناعدد," IsCondition="False" IsForce="False" VS="False" ISFormulla="False" VF="0" ReadOnly="False" />
</Grid>
</GridBinding>
I want this result:
var object = {
"grd1": [ {
ID: "ID",
Visible: "True",
FieldId: "1",
IsForce: "false",
ReadOnly="true"
} ],
};
This is my code:
if ((item as XmlElement).Attributes["Type"].Value == "Grid") {
if (Id_elem == (itemgrigIn as XmlElement).Attributes["ID"].Value) {
if (Orientation == "Horizontal" || Orientation == "" || Orientation == null) {
s += " <div id=" + Id_elem + "myDiv" +
" dir='rtl' align='center' class='table-responsive'></div> " +
" <script> $(document).ready(function() {var " +
Id_elem + "Divresult = $(" + "'" + "<div id=" +
Id_elem + "Div" + " ></div>);" +
"'" + " $(" + Id_elem + "Div" + ").append(" +
Id_elem + "Divresult); var " +
Id_elem + " = new grid(" + "'" + Id_elem + "'" +
"," + countgrid + ");" + Id_elem +
".init(); }); </script> ";
}
}
}
It is not trivial task. If you want make all right You must first create a parser from xaml string to object. And then parser from object to json string. You must research and find libs to convert xml and json.
hi iam sloved this problem
1- first use XmlNode
public string CreateHtml(Form formInfo, XmlNode _MainNode,string oldHtml)
{
ConvertXmlToHtml(_MainNode, ref Result);
}
public void ConvertXmlToHtml(XmlNode XmlElement, ref string s)
{
PropertyInfo _propList = new PropertyInfo();
#region grid for create arrye
foreach (XmlNode item in XmlElement.ChildNodes)
{
if (item.Name == "AvailableItems" || item.Name == "DataSource" || item.Name == "GridBinding")
{
continue;
}
if ((item as XmlElement).Attributes["Type"].Value == "Grid")
{
string Id_elem = (item as XmlElement).Attributes["ID"].Value;
foreach (XmlNode itemgrigOut in XmlElement.ChildNodes)
{
if (itemgrigOut.Name == "GridBinding")
{
countgrid++;
if (countgrid < 2)
s += "<script> $(document).ready(function() { var object_grid = {" ;
foreach (XmlNode itemgrigIn in itemgrigOut)
{
if (Id_elem == (itemgrigIn as XmlElement).Attributes["ID"].Value)
{
s += Id_elem + " :[ ";
if (Orientation == "Horizontal" || Orientation == "" || Orientation == null)
{
//ساخت گرید مورد نظر
}
else
{
foreach (XmlNode itemcildgrid in itemgrigIn)
{
if ((itemcildgrid as XmlElement).Attributes[Properties.Resources.PropertiesInfo] != null)
_propList = new PropertyInfo() { PropertyList = (itemcildgrid as XmlElement).Attributes[Properties.Resources.PropertiesInfo].Value };
s += " { ID : " + ReturnAttribute((itemcildgrid as XmlElement), "IDgrid", false);
s += ", Visible : " + ReturnAttribute((itemcildgrid as XmlElement), "Visible", false);
s += ", VisibleIndex : " + ReturnAttribute((itemcildgrid as XmlElement), "VisibleIndex", false);
s += ", ReadOnly : " + ReturnAttribute((itemcildgrid as XmlElement), "ReadOnly", false);
s += ", SortOrder : " + ReturnAttribute((itemcildgrid as XmlElement), "SortOrder", false);
s += ", Mask : " + ReturnAttribute((itemcildgrid as XmlElement), "Mask", false);
s += ", IsCondition : " + ReturnAttribute((itemcildgrid as XmlElement), "IsCondition", false);
s += ", ISFormulla : " + ReturnAttribute((itemcildgrid as XmlElement), "ISFormulla", false);
s += ", ReadOnly : " + ReturnAttribute((itemcildgrid as XmlElement), "ReadOnly", false);
s += ", IsForce : " + ReturnAttribute((itemcildgrid as XmlElement), "IsForcegrid", false);
s += "}, ";
}
s += "], ";
}
}
}
}
}
}
}
if (countgrid == CountAll_grid)
s += " } }); </script> ";
#endregion
#region grid
foreach (XmlNode item in XmlElement.ChildNodes)
{
childCount++;
if (item.Name == "AvailableItems" || item.Name == "DataSource" || item.Name == "GridBinding")
{
continue;
}
if ((item as XmlElement).Attributes["Type"].Value == "Grid")
{
string Id_elem = (item as XmlElement).Attributes["ID"].Value;
foreach (XmlNode itemgrigOut in XmlElement.ChildNodes)
{
if (itemgrigOut.Name == "GridBinding")
{
//شمارش تعداد گریدها
countgrid++;
if (countgrid ==0)
{ }
foreach (XmlNode itemgrigIn in itemgrigOut)
{
if (Id_elem == (itemgrigIn as XmlElement).Attributes["ID"].Value)
{
if (Orientation == "Horizontal" || Orientation == "" || Orientation == null)
{
//ساخت گرید مورد نظر
s += string.Format("<br/><div dir = 'rtl' align = 'center' class='table-responsive'><div class='row well'>" +
"<table id=" + Id_elem + "cellpadding='0' cellspacing='0'></table> <div id = pager_" + Id_elem + "></div></div></div>"
);
}
else
{
s += " <div id=" + Id_elem + "myDiv" + " dir='rtl' align='center' class='table-responsive'></div> " +
" <script> $(document).ready(function() {var " + Id_elem + "Divresult = $(" + "'" + "<div id=" + Id_elem + "Div" + " ></div>" + "'" + ") ; " +
" $(" + Id_elem + "Div" + ").append(" + Id_elem + "Divresult); var " + Id_elem + " = new grid(" + "'" + Id_elem + "'" + "," + countgrid + ");" + Id_elem + ".init(); }); </script> ";
$(document).ready(function() {var object_grid = {" + Id_elem +" :[ ";
}
}
}
}
}
}
#endregion
}

How to save Data In Database to the controller

How to save Data In Database to the controller.i am using jquery to get data from the textbox. please help me.
Contactcontroller.cs
public ActionResult Create(string Name, string Company, string
Regarding, string Email, string Phone, string Message) {
string body = "Name: " + Name + "<br>" + "\nCompany: " + Company + "<br>" + "Regarding: " + Regarding + "<br>" + "Email: " +
Email + "<br>" + "Phone: " + Phone + "<br>" + "Message: " + Message;
try
{
// code
}
catch
{
}
jquery.js
$("#btnSubmit").click(function (event) {
var data = { Name: $("#txtbxName").val(), Company: $("#txtbxCompany").val(), Regarding:
$("#ddlRegarding").val(), Email: $("#txtbxEmail").val(), Phone: $("#txtbxPhone").val(), Message:
$("#txtarMessage").val()
}
$.ajax({
type: "POST",
url: "/Contact/Create", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
dataType: "html",
success: function (result) {
$("#txtarMessage").val("");
alert(result);
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function (result) {
alert('Thanks for sending info');
location.reload();
return false;
}
});
});
i am getting data to the textbox using jquery.
now i want to save the whole data in the database through Controller.
Jquery
$.post('/Controller/Create', { Name: $('#Name').val(), Company: "Company", Regarding: "", Email: "",Phone: "",Message: ""}, function (data) {
});
Controller Action
public JsonResult Create(string Name, string Company, string Regarding, string Email, string Phone, string Message)
{
string body = "Name: " + Name + "<br>" + "\nCompany: " + Company + "<br>" + "Regarding: " + Regarding + "<br>" + "Email: " +
Email + "<br>" + "Phone: " + Phone + "<br>" + "Message: " + Message;
return Json(body, JsonRequestBehavior.AllowGet);
}

Categories

Resources