Convert Json to explicit new object, List initialization c# - 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

Related

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 can I parse JSON to a C# object?

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.

How to read specific Json object from Json string in C#?

Following is the JSON string:
{
"ios_info": {
"serialNumber": "F2LLMBNJFFF",
"imeiNumber": "01388400413235",
"meid": "",
"iccID": "8901410427640096045",
"firstUnbrickDate": "11/27/13",
"lastUnbrickDate": "11/27/13",
"unbricked": "true",
"unlocked": "false",
"productVersion": "7.1.2",
"initialActivationPolicyID": "23",
"initialActivationPolicyDetails": "US AT&T Puerto Rico and US Virgin Islands Activation Policy",
"appliedActivationPolicyID": "23",
"appliedActivationDetails": "US AT&T Puerto Rico and US Virgin Islands Activation Policy",
"nextTetherPolicyID": "23",
"nextTetherPolicyDetails": "US AT&T Puerto Rico and US Virgin Islands Activation Policy",
"macAddress": "ACFDEC6C988A",
"bluetoothMacAddress": "AC:FD:EC:6C:98:8B",
"partDescription": "IPHONE 5S SPACE GRAY 64GB-USA"
},
"fmi": {
"#attributes": {
"version": "1",
"deviceCount": "1"
},
"fmipLockStatusDevice": {
"#attributes": {
"serial": "F2LLMBNJFFFQ",
"imei": "013884004132355",
"isLocked": "true",
"isLost": "false"
}
}
},
"product_info": {
"serialNumber": "F2LLMBNJFFFQ",
"warrantyStatus": "Apple Limited Warranty",
"coverageEndDate": "11/25/14",
"coverageStartDate": "11/26/13",
"daysRemaining": "498",
"estimatedPurchaseDate": "11/26/13",
"purchaseCountry": "United States",
"registrationDate": "11/26/13",
"imageURL": "http://service.info.apple.com/parts/service_parts/na.gif",
"explodedViewURL": "http://service.info.apple.com/manuals-ssol.html",
"manualURL": "http://service.info.apple.com/manuals-ssol.html",
"productDescription": "iPhone 5S",
"configDescription": "IPHONE 5S GRAY 64GB GSM",
"slaGroupDescription": "",
"contractCoverageEndDate": "11/25/15",
"contractCoverageStartDate": "11/26/13",
"contractType": "C1",
"laborCovered": "Y",
"limitedWarranty": "Y",
"partCovered": "Y",
"notes": "Covered by AppleCare+ - Incidents Available",
"acPlusFlag": "Y",
"consumerLawInfo": {
"serviceType": "",
"popMandatory": "",
"allowedPartType": ""
}
}
}
Following Reads ALLJSON in Key:Value and displays in table format But i need only specific object i.e FMI section of json string only:
private string GetKeyValuePairs(string jsonString)
{
var resDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
string sdict = string.Empty;
string fmitxt = string.Empty;
string fmitxt2 = string.Empty;
foreach (string key in resDict.Keys)
{
sdict += "<tr><td> " + key + "</td> " + (resDict[key].GetType() == typeof(Newtonsoft.Json.Linq.JObject) ? "<td>" + GetKeyValuePairs(resDict[key].ToString()) + "</td></tr>" : "<td>" + resDict[key].ToString() + "</td></tr>");
}
return sdict;
}
Problem:
I want to read ALL the content of "fmi" section only. and display in key:Value. table format
NOTE:
I am using Framework 3.5 hence cant use dynamic keyword.
Any idea?
I'd recommend that you work with it as a JObject directly; this is the class you'd be using behind-the-scenes if you were using dynamic. Also, you need to separate out the selection of fmi from the normal path done in the recursive calls: here I have it in Main.
void Main()
{
var resObj = JsonConvert.DeserializeObject<JObject>(jsonString);
var result = GetKeyValuePairs((JObject)resObj["fmi"]);
}
private string GetKeyValuePairs(JObject resObj)
{
string sDict = string.Empty;
string fmitxt = string.Empty;
string fmitxt2 = string.Empty;
foreach (var pair in resObj)
{
sDict += "<tr><td> " + pair.Key + "</td>";
if (pair.Value is JObject)
sDict += "<td>" + GetKeyValuePairs((JObject)pair.Value) + "</td></tr>";
else
sDict += "<td>" + pair.Value.ToString() + "</td></tr>";
}
return sDict;
}
Since you are not deserializing this into a "strong typed" object you can do something like this:
var fmi = JsonConvert.DeserializeObject<Dictionary<string,object>>(str)["fmi"];
var keys = JsonConvert.DeserializeObject<Dictionary<string, object>>(fmi.ToString());
This can be solved accurately with this method, just keep in mind, you will need Newtonsoft.Json;
//using Newtonsoft.Json;
// using System.IO;
string dataPath = #"myfile.json"; // Location of the json
string jsonData = "";
using (StreamReader r = new StreamReader(Path.Combine(dataPath)))
{
string json = r.ReadToEnd();
jsonData = json;
}
dynamic obj = JsonConvert.DeserializeObject(jsonData);
string value = obj["name"]; // here name is the object name holding the required data
Console.WriteLine(value);
Console.ReadLine();
/*
* OUTPUT
* itzplayz
*/
Here's the JSON Example
{
"name": "itzplayz"
}
Now you can get the value of the JSON object in the string called value

Why is the href of anchor tag written in code behind not accepting 'aspx'

I have a calender control and on selecting a respective date, I need to display Today's Due and Over due as two section in an accordion. I have written the div for accordion in code behind and set style.css to give the look of Accordion. The data from code behind is converted into json and displayed. The code behind is as follows:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CalenderBinderAccordian()
{
try
{
//Code to fetch productGroup is not shown
foreach (var p in productGroup)
{
var todoCount = 1;
string todoString = "";
int uniqueID = Guid.NewGuid().GetHashCode();
todoString = "<div class='accordion vertical'><section id='" + uniqueID + "' style='overflow-y: scroll;'> <h2><b>Due Today</b></h2>";
foreach (var t in p.todo)
{
var tempAmt = String.Empty;
if ((t.Amount == null) || t.Amount == String.Empty)
tempAmt = "0";
else
tempAmt = Convert.ToDecimal(t.Amount.ToString()).ToString();
todoString += "<p><div style='padding:5px 0px; border-bottom:dashed 1px #dddddd;'><b>" + todoCount.ToString() + "</b>. " + t.ProductName + "<span style='text-align:right; padding-right:5px;'> $" + tempAmt + "</span><a href='www.google.com' target='_blank' style='text-decoration:none;'><b>Pay Now</b></a></div></p>";
todoCount++;
}
todoString += "</section>";
var overDue = temps.Select(x => new { x.DueDate }).Distinct().ToList();
int overDueCount = 0;
uniqueID = Guid.NewGuid().GetHashCode();
todoString += "<section id='" + uniqueID + "'> <h2><b>Over Due</b></h2>";
int todoCount1 = 1;
for (int i = 0; i < overDue.Count(); i++)
{
if ((Convert.ToDateTime(overDue[i].DueDate) - Convert.ToDateTime(p.dates)).Days < 0)
{
overDueCount++;
var overDueList = temps.FindAll(x => x.DueDate.Equals(overDue[i].DueDate)).ToList();
foreach (var t in overDueList)
{
var tempAmt = String.Empty;
if ((t.Amount == null) || t.Amount == String.Empty)
tempAmt = "0";
else
tempAmt = Convert.ToDecimal(t.Amount.ToString()).ToString();
//Error occurs when the href is given as aspx
todoString += "<p><div style='padding:5px 0px; border-bottom:dashed 1px #dddddd;'><b>" + todoCount1.ToString() + "</b>. " + t.ProductName + "<span style='text-align:right; padding-right:5px;'> $" + tempAmt + "</span><a href='PaymentDetails.aspx' target='_blank' style='text-decoration:none;'><b>Pay Now</b></a></div></p>";
todoCount++;
todoCount1++;
}
}
}
todoString = todoString + "</section></div>\",\"count\":\"" + todoCount + "\"},";
jsonString = jsonString + String.Format("{{\"{0}\" : \"{1}\",\"{2}\" : \"{3}", "dates", p.dates, "todo", todoString);
if (overDueCount.Equals(0))
{
jsonString = jsonString.Replace("</section><section id='" + uniqueID + "'> <h2><b>Over Due</b></h2></section>", "</section>");
}
}
jsonString = jsonString.TrimEnd(',');
jsonString = '[' + jsonString + ']';
string data= jsonString; JavaScriptSerializer().Serialize(productGroup);
return data;
}
catch (Exception ex)
{
throw;
}
}
//How to data is converted to Jsonvar tododate = [];
$(window).bind('loaded', function () {
$.ajax({
type: "POST",
url: "ChartBinder.asmx/CalenderBinderAccordian",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
tododate = JSON.parse(msg.d);
},
error: function (msg) {
alert("error");
}
});
});
Kindly note when the href is given as www.google.com the functionality works well but when it is given as PaymentGateway.aspx It does not display date in accordion format rather shows error alert.
Using Firebug, Noticed the following Error:
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property
Solution: Tried changing the configuration :
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>

sorting in asp.net

var store = new FMP.AspNetJsonStore({
fields: [
{ name: 'AssetID' },
{ name: 'AssociationID' },
{ name: 'Image' },
{ name: 'StatusName' },
{ name: 'ModelName' },
{ name: 'IPAddress' },
{ name: 'InScope', type: 'boolean' },
{ name: 'ServicePlanName' },
{ name: 'PricePlanName' },
{ name: 'PricePlanDescription' },
{ name: 'Program' },
{ name: 'ServicePlanID' },
{ name: 'Customer' },
{ name: 'Black', type: 'float' },
{ name: 'Cyan', type: 'float' },
{ name: 'Magenta', type: 'float' },
{ name: 'Yellow', type: 'float' },
{ name: 'BlackPct' },
{ name: 'CyanPct' },
{ name: 'MagentaPct' },
{ name: 'YellowPct' },
{ name: 'PrinterMarkerSupplies' },
{ name: 'PageCount' },
{ name: 'BlackImpressions' },
{ name: 'ColorImpressions' },
{ name: 'PricePlanID' },
{ name: 'ResponsibilityForAction' },
{ name: 'PrinterSerialNumber' }
],
totalProperty: "TotalCount",
autoLoad: { params: { start: 0, limit: myPageSize} },
//autoLoad: true,
proxy: new Ext.data.HttpProxy({
// Call web service method using GET syntax
url: 'GetPrintersGrid.asmx/buildGrid',
// Ask for Json response
headers: { 'Content-type': 'application/json' },
method: "GET"
}),
remoteSort: true,
//sortInfo: { field: 'PageCount', direction: "DESC" },
groupField: 'Customer',
root: 'Records'
});
store.setDefaultSort('PageCount', 'DESC');
Here is the web service i used
public PagedResult<FMPAsset> buildGrid(int start, int limit, string sortfield, string dir)
{
var a=5;
Guid AccountID = (Guid)Session["AccountID"];
//string sortdir;
//if( dir == "DESC")
//{
// sortdir = dir.Substring(0, 4).Trim().ToUpper();
//}
//else
//{
// sortdir = dir.Substring(0, 3).Trim().ToUpper();
//}
string SortExpression = sortfield + " " + (!String.IsNullOrEmpty(dir) ? dir : String.Empty);
//string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "' order by a.PageCount = '" + + "'";
string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "' Order By a."+SortExpression;
//string whereClause = "SELECT value a , ROW_NUMBER() OVER(ORDER BY"
// + " " + SortExpression
// + ") As RowNumber FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'"
// + AccountID + "'";
//string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "'";
List<FMPAsset> fmpAssets = new List<FMPAsset>();
using (XSPAssetModel.XSPAssetEntities assetEntities = new XSPAssetEntities(b.BuildEntityConnectionString1("XSMDSN")))
{
ObjectQuery<XSP_AssetList_V> assets = new ObjectQuery<XSP_AssetList_V>(whereClause, assetEntities);
//var assetOrder = assets.OrderBy(x => x.StatusName).ToList();
var assetPage = assets.Skip(start).Take(limit);
//var totalAssetCount = assets.Count();
currentAssets = assetPage.ToList();
int currentAssetsCount = currentAssets.Count;
string imgprefix = System.Configuration.ConfigurationManager.AppSettings["ImgPrefix"];
char[] separators = { '/' };
string appname = "";
int lastloc = imgprefix.Substring(0, imgprefix.Length - 1).LastIndexOfAny(separators);
if (lastloc > 6)
{
appname = imgprefix.Substring(lastloc + 1);
}
FMPAsset asset = new FMPAsset();
//StreamWriter sw = new StreamWriter("C:\\test.txt");
XSPPrinterMarkerSupplyModel.XSPPrinterMarkerSupplyEntities markerCtx =
new XSPPrinterMarkerSupplyModel.XSPPrinterMarkerSupplyEntities(b.BuildEntityConnectionString1("XSMDSN"));
for (int x = 0; x < currentAssetsCount; x++)
{
asset = new FMPAsset();
asset.AssetID = currentAssets[x].AssetID.ToString();
asset.PricePlanID = currentAssets[x].PricePlanID.ToString();
asset.AssociationID = currentAssets[x].AssociationID;
asset.ModelName = currentAssets[x].ModelName;
asset.ResponsibilityForAction = currentAssets[x].ResponsibilityForAction;
asset.IPAddress = (String.IsNullOrEmpty(currentAssets[x].PrinterIPAddress)) ? "No IP" : currentAssets[x].PrinterIPAddress; ;
if (currentAssets[x].InScope)
{
asset.InScope = b.GetString("SDE_YES");
}
else
{
asset.InScope = b.GetString("SDE_NO");
}
asset = SetStatus(appname, asset, x);
asset.PricePlanName = currentAssets[x].Program;
asset.PricePlanDescription = currentAssets[x].PricePlanDescription;
asset.ServicePlanName = currentAssets[x].ServicePlanName;
if (currentAssets[x].PrinterSerialNumber != null)
{
asset.PrinterSerialNumber = currentAssets[x].PrinterSerialNumber;
}
else
{
asset.PrinterSerialNumber = "-";
}
//sw.WriteLine("ChargebackDescription: " + DateTime.Now.Millisecond);
if (this.b.UseChargebackDescription
&& !String.IsNullOrEmpty(currentAssets[x].CustomerChargebackDescription)
&& currentAssets[x].CustomerChargebackDescription != "Generated by OUT Integration")
{
asset.Customer = currentAssets[x].CustomerChargebackDescription;
if (asset.Customer.IndexOf(Environment.NewLine) > -1)
{
asset.Customer =
asset.Customer.Substring(0, asset.Customer.IndexOf(Environment.NewLine));
}
}
else
{
asset.Customer = currentAssets[x].CustomerChargeBackEntryName;
}
if (this.b.UsePricePlanDescription && !String.IsNullOrEmpty(currentAssets[x].PricePlanDescription))
{
asset.Program = currentAssets[x].PricePlanDescription;
if (asset.Program.IndexOf(Environment.NewLine) > -1)
{
asset.Program =
asset.Program.Substring(0, asset.Program.IndexOf(Environment.NewLine));
}
}
else
{
asset.Program = currentAssets[x].Program;
}
asset.BlackPct = -3;
asset.CyanPct = -3;
asset.MagentaPct = -3;
asset.YellowPct = -3;
Guid id = currentAssets[x].AssetID;
asset = SetCMYKvalues(asset, x);
BuilldImpressionsValues(currentAssets[x], ref asset);
fmpAssets.Add(asset);
}
//CommonGrid1.ApplyUserPreferences();
//JavaScriptSerializer json = new JavaScriptSerializer();
//string JsonArray = json.Serialize(fmpAssets);
//string ArrayDeclaration = string.Format("var arr = {0};", JsonArray);
//Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "fmpAssets", ArrayDeclaration, true);
//assetEntities.Dispose();
var totalAssetCount = assets.Count();
var y = new PagedResult<FMPAsset>();
y.Records = fmpAssets;
y.TotalCount = totalAssetCount;
return y;
// CommonGrid1.BindDataSource(SortByStatusName(fmpAssets));
}
}
I am getting an error saying:
{"Message":"Invalid JSON primitive:
DESC.","StackTrace":" at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n
at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32
depth)\r\n at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String
input, Int32 depthLimit,
JavaScriptSerializer serializer)\r\n
at
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer
serializer, String input, Type type,
Int32 depthLimit)\r\n at
System.Web.Script.Services.RestHandler.GetRawParamsFromGetRequest(HttpContext
context, JavaScriptSerializer
serializer, WebServiceMethodData
methodData)\r\n at
System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData
methodData, HttpContext context)\r\n
at
System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
context, WebServiceMethodData
methodData)","ExceptionType":"System.ArgumentException"}
Can anyone help me in this issue?
Sure Here is the JSON store
Ext.ns("FMP");
FMP.AspNetJsonReader = Ext.extend(Ext.data.JsonReader, {
read: function(response) {
// Assuming ASP.NET encoding - Data is stored as
var json = response.responseText;
var o = Ext.decode(json);
if (!o) {
throw { message: "AspNetJsonReader.read: Json object not found" };
}
if (!o.d) {
throw { message: "AspNetJsonReader.read: Root element d not found" };
}
return this.readRecords(o.d);
}
});
FMP.AspNetJsonStore = Ext.extend(Ext.data.GroupingStore, {
/**
* #cfg {Ext.data.DataReader} reader #hide
*/
constructor: function(config) {
FMP.AspNetJsonStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new FMP.AspNetJsonReader(config)
}));
}
});

Categories

Resources