Json data not well formated error - html

json data not binding into table
controller code
$http(
{
method: 'post',
url: 'Service.asmx/WPGetDS',
data: $.param({ as_sql: "select * from testtab", strConKey: "Etech" }),
dataType: 'json',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data, status, headers, config) {
var myjson = JSON.parse(data);
$scope.dtDioSearch = myjson;
console.log(myjson);
}).error(function (data, status, headers, config) {
console.log(data);
});
Web Service Code
Public Sub WPGetDS(ByVal as_sql As String, ByVal strConKey As String)
Dim dt As New DataTable()
Dim conGlobal As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings(strConKey).ConnectionString)
Dim a(0) As String
Dim dr As DataRow
Dim dtDataTable As DataTable
If conGlobal.State = ConnectionState.Closed Then conGlobal.Open()
Dim SDA = New SqlDataAdapter(as_sql, conGlobal)
Dim DS As DataSet = New DataSet()
Dim data As New WPData
Dim js As New JavaScriptSerializer()
Dim lCmdSql, lCmdErr As New SqlCommand
Try
dtDataTable = New DataTable("Table")
Dim dcolSrNo As DataColumn
dcolSrNo = New DataColumn("SlNo")
dcolSrNo.AutoIncrement = True
dcolSrNo.AutoIncrementSeed = 1
dcolSrNo.AutoIncrementStep = 1
dtDataTable.Columns.Add(dcolSrNo)
DS.Tables.Add(dtDataTable)
SDA.Fill(DS, ("Table"))
SDA.Dispose()
data.Message = ConvertDataTableTojSonString(DS.Tables(0))
Context.Response.Write(js.Serialize(data.Message))
Catch ex As Exception
dt.Columns.Clear()
dt.Columns.Add("Error")
dr = dt.NewRow
dr.Item("Error") = ex.Message.Trim
dt.Rows.Add(dr)
DS.Tables.Add(dt)
conGlobal.Close()
data.Message = ConvertDataTableTojSonString(DS.Tables(0))
Context.Response.Write(js.Serialize(data.Message))
Finally
If conGlobal.State = ConnectionState.Open Then conGlobal.Close()
End Try
End Sub
HTML Code
<div class="table-responisive">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Test</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="erdata in dtDioSearch track by $index">
<td>{{erdata.SlNo}}</td>
<td>{{erdata.Test}}</td>
</tr>
</tbody>
</table>
</div>
Console Json data
[{"SlNo":1,"test":"test"},{"SlNo":2,"test":"test"},{"SlNo":3,"test":"test"},{"SlNo":4,"test":"test"},{"SlNo":5,"test":"test"},{"SlNo":6,"test":"test"},{"SlNo":7,"test":"test"},{"SlNo":8,"test":"test"},{"SlNo":9,"test":"test"},{"SlNo":10,"test":"test"},{"SlNo":11,"test":"test"},{"SlNo":12,"test":"test"},{"SlNo":13,"test":"test"},{"SlNo":14,"test":"test"},{"SlNo":15,"test":"test"},{"SlNo":16,"test":"test"},{"SlNo":17,"test":"test"},{"SlNo":18,"test":"test"},{"SlNo":19,"test":"test"},{"SlNo":20,"test":"test"},{"SlNo":21,"test":"test"},{"SlNo":22,"test":"test"}]
My problem is json data not bind to the html table. in firefox there was an error shown not well-formed in console. please help...

The first argument of your success callback will be a JavaScript object containing many properties including a data property whose value is the parsed JavaScript object based on the JSON returned by your API. Trying to parse a JavaScript object will result in error.
Try modifying the success method to:
.success(function (response, status, headers, config) {
var myjson = response.data;
$scope.dtDioSearch = myjson;
});

Public Function GetJSon(ByVal dt As DataTable) As List(Of Dictionary(Of String, Object))
Dim rows As New List(Of Dictionary(Of String, Object))
Dim row As Dictionary(Of String, Object)
'Return JsonConvert.SerializeObject(dt).ToList
'Return JSONString
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)
For Each col As DataColumn In dt.Columns
If col.DataType = GetType(Date) Then
Dim dtt As DateTime = DateTime.Parse(dr(col).ToString())
row.Add(col.ColumnName, dtt.ToString("dd-MM-yyyy hh:mm:ss"))
Else
row.Add(col.ColumnName, dr(col))
End If
Next
rows.Add(row)
Next
Return rows
End Function
#tj thank you for your support. the problem is json return string and i changed it to array list

Related

How to get a list records in 1c from JSON data

I get JSON data in 1C from the address written below. There is no problem when there is only one registration. But I cannot list many records. It gives an error "Object field not found (Key)." What do I have to do to list the records? Help, please.
Host = "jsonplaceholder.typicode.com/";
HTTPRequest = New HTTPRequest;
// HTTPRequest.ResourceAddress = "todos/1";
HTTPRequest.ResourceAddress = "photos/" ;// ThisObject.Attribute2;
HTTPConnection = New HTTPConnection(host,,,,,10,New OpenSSLSecureConnection);
HTTPAnswer = HTTPConnection.Get(HTTPRequest);
stringAnswer= HTTPAnswer.GetBodyAsString();
JSONReader = New JSONReader;
JSONReader.SetString(stringAnswer);
JsonResult = ReadJson(JSONReader,True);
For each strResult in JsonResult Do
If (strResult.Key = "url") Then
Message(strResult.Value);
EndIf;
EndDo;
Your code should be like this:
Host = "jsonplaceholder.typicode.com/";
HTTPRequest = New HTTPRequest;
HTTPRequest.ResourceAddress = "photos/" ;
HTTPConnection = New HTTPConnection(host,,,,,10,New OpenSSLSecureConnection);
HTTPAnswer = HTTPConnection.Get(HTTPRequest);
stringAnswer = HTTPAnswer.GetBodyAsString();
JSONReader = New JSONReader;
JSONReader.SetString(stringAnswer);
JsonResult = ReadJson(JSONReader,True);
For each strResult in JsonResult Do
For Each curElement In strResult Do
If (curElement.Key = "url") Then
Message(curElement.Value);
Break; // since the value curElement.Key = "url" can be only once, we can exit the loop
EndIf;
EndDo;
EndDo;
­
JsonResult is an array of values (see scr.1). Each element of the array is a map strResult (scr.2). First, in a loop, we iterate over all the elements of the array, and in a nested loop, we iterate over the matching fields.
use curElement.get("Key")
it another type of data

UPDATE: Azure DevOps API: Sending commands to the REST API that are JSON instead of a URI

I am a little new to using the REST API for Azure DevOps and have it working fine where I can send my requests that are basically the URIs I see on the website for the API. Then I get that JSON response and de-serialize it into a class from the JSON response and am off running.
Below is an example of a function I use to get a Work Item by it's ID. It uses the URI from the website.
I can also test things by pasting the URI into my browser and then see the response.
My question is, How do I use the command for Updating the Workitem (Add Link for example) which is not a URI that I can test by pasting it into my browser. Instead it is a JSON message.
here is API Website which shows the JSON message needed to add a link to a work item.
https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/update?view=azure-devops-rest-5.1#add-a-link
this is the JSON message they have there for updating a WorkItem Link:
[
{
"op": "test",
"path": "/rev",
"value": 3
},
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "System.LinkTypes.Dependency-forward",
"url": "https://dev.azure.com/fabrikam/_apis/wit/workItems/300",
"attributes": {
"comment": "Making a new link for the dependency"
}
}
}
]
Do I need a different function to send it the JSON message and then the function could return me the JSON Response? I can not find an example of what that function might look like.
Any Advice on how to send the JSON message instead of the URI to get a response would be greatly appreciated.
===================== UPDATE =====================
The one answer definitely helped me get this finally working.
I pasted in the updated function in case it helps anyone else.
I know it is tricky to find VB.NET samples for this. :)
THANKS!
UPDATED CODE==========================================================
Public Async Function GetRequestAsync(ByVal uri As String, Optional ByVal jsonMessageBody As String = "") As Task(Of String())
Dim client As HttpClient = New HttpClient()
SetUpHttpClient(client)
Dim statusCode As String = "NOTHING"
Dim responseBody As String = "NOTHING"
Try
If jsonMessageBody.Length > 0 Then
'#####################################################################
'### For all PATCH operations that have a URI and a JSON message ###
'#####################################################################
Dim patchValue = New StringContent(jsonMessageBody, Encoding.UTF8, "application/json-patch+json")
Dim method = New HttpMethod("PATCH")
Dim request = New HttpRequestMessage(method, uri) With {.Content = patchValue}
Dim response = client.SendAsync(request).Result
responseBody = response.Content.ReadAsStringAsync.Result()
Else
'#######################################################
'### For all other operations that have just a URI ###
'#######################################################
Using response As HttpResponseMessage = client.GetAsync(uri).Result
statusCode = response.StatusCode.ToString()
response.EnsureSuccessStatusCode()
responseBody = response.Content.ReadAsStringAsync().Result
End Using
End If
Catch
End Try
Dim answer As String() = {statusCode, responseBody}
Return answer
End Function
Public Function GetTestCase(organization As String, project As String, TestCaseID As String) As WorkItemApi
Dim dc As New DevCon.DevOpsConnector
Dim response As String() = dc.GetRequest($"https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{TestCaseID}?api-version=5.1&$expand=all")
If response(0) <> "OK" Then
Return Nothing
End If
Dim result As WorkItemApi = JsonConvert.DeserializeObject(Of WorkItemApi)(response(1))
Return result
End Function
Public Async Function GetRequestAsync(ByVal getRequest As String) As Task(Of String())
Dim client As HttpClient = New HttpClient()
SetUpHttpClient(client)
Dim statusCode As String = "NOTHING"
Dim responseBody As String = "NOTHING"
Try
Using response As HttpResponseMessage = client.GetAsync(getRequest).Result
statusCode = response.StatusCode.ToString()
' Console.WriteLine("Response: " & statusCode)
response.EnsureSuccessStatusCode()
responseBody = response.Content.ReadAsStringAsync().Result
End Using
Catch
End Try
Dim answer As String() = {statusCode, responseBody}
Return answer
End Function
You need to serialize the fields array into a json string. Check the following sample in C# using the HttpClient class:
public WorkItem CreateBugUsingHTTP()
{
string uri = _uri;
string personalAccessToken = _personalAccessToken;
string project = _project;
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken)));
Object[] patchDocument = new Object[4];
patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = "Authorization Errors" };
patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", value = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http://msdn.microsoft.com/en-us/library/live/hh826547.aspx" };
patchDocument[2] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "1" };
patchDocument[3] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Severity", value = "2 - High" };
using (var client = new HttpClient())
{
//set our headers
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
//serialize the fields array into a json string
var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");
var method = new HttpMethod("POST");
var request = new HttpRequestMessage(method, uri + "/" + project + "/_apis/wit/workitems/$Bug?api-version=5.1") { Content = patchValue };
var response = client.SendAsync(request).Result;
//if the response is successfull, set the result to the workitem object
if (response.IsSuccessStatusCode)
{
var workItem = response.Content.ReadAsAsync<WorkItem>().Result;
Console.WriteLine("Bug Successfully Created: Bug #{0}", workItem.Id);
return workItem;
}
else
{
Console.WriteLine("Error creating bug: {0}", response.Content);
return null;
}
}
}
You could get started from the documentation below:
https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1
Public Async Function GetRequestAsync(ByVal uri As String, Optional ByVal jsonMessageBody As String = "") As Task(Of String())
Dim client As HttpClient = New HttpClient()
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", _accessTokenHttpClient)
Dim statusCode As String = "NOTHING"
Dim responseBody As String = "NOTHING"
Try
If jsonMessageBody.Length > 0 Then
'#####################################################################
'### For all PATCH operations that have a URI and a JSON message ###
'#####################################################################
Dim patchValue = New StringContent(jsonMessageBody, Encoding.UTF8, "application/json-patch+json")
Dim method = New HttpMethod("PATCH")
Dim request = New HttpRequestMessage(method, uri) With {.Content = patchValue}
Dim response = client.SendAsync(request).Result
responseBody = response.Content.ReadAsStringAsync.Result()
Else
'#######################################################
'### For all other operations that have just a URI ###
'#######################################################
Using response As HttpResponseMessage = client.GetAsync(uri).Result
statusCode = response.StatusCode.ToString()
response.EnsureSuccessStatusCode()
responseBody = response.Content.ReadAsStringAsync().Result
End Using
End If
Catch
End Try
Dim answer As String() = {statusCode, responseBody}
Return answer
End Function

Long polling: Max Pool size reached

I'm using long polling in my website to check for any new data in MySQL database and then updating the ui,
actually if the website is up for longer than +- one hour the website just broke up by giving the following error:
500 {"Message":"error connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.","StackTrace":" at MySql.Data.MySqlClient.MySqlPool.GetConnection()\r\n at MySql.Data.MySqlClient.MySqlConnection.Open()\r\n at VisualReservation._Default.getSale() in C:\\Users\\imytyuk\\Documents\\Visual Studio 2017\\Projects\\VisualReservation\\VisualReservation\\Default.aspx.vb:line 109","ExceptionType":"MySql.Data.MySqlClient.MySqlException"}
So it seems that there are too many connections to the database and it just get broken..
Actually the error is thrown by the following method that is called from long polling
function getTavoli(data_tavoli, salaSelect, pooling) {
$.ajax({
type: "POST",
url: "Default.aspx/SetTavoli",
data: JSON.stringify({ data: moment(data_tavoli).format('YYYY-MM-DD') }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var ingiorno = $('#ingiorno').val();
var fngiorno = $('#fngiorno').val();
var insera = $('#insera').val();
var fnsera = $('#fnsera').val();
ingiorno = ingiorno.split(":")[0];
fngiorno = fngiorno.split(":")[0];
insera = insera.split(":")[0];
fnsera = fnsera.split(":")[0];
if ($('#titleTurni').attr('data-turno') == "giorno") {
Range = ingiorno * 4
Fine = (fngiorno * 4) + 1;
orainizio = ingiorno;
orafine = fngiorno;
} else {
Range = insera * 4
Fine = (fnsera * 4) + 1;
orainizio = insera;
orafine = fnsera;
}
data = r.d;
data = $.parseJSON(data);
if (pooling) {
if (JSON.stringify(data) === prevData) {
return;
} else {
recreateTabs();
prevData = JSON.stringify(data);
}
}
$('#listBodyMobile').empty();
$('#bodyGiorno').empty();
$('#bodySera').empty();
getInfo(data_tavoli);
$.each(data, function (i, item) {
// doing all stuff with items
});
});
},
error: function (xhr, status, errorThrow) {
console.log(xhr.status + " " + xhr.responseText);
}
});
}
The polling is called in the following way
poolingTav = setInterval(() => {
getTavoli(new Date($("#day").attr('data-giorno')), $("#titleSale").attr('data-numsala'), true);
}, 50000)
While the SetTavoli in the server side looks like the following
<WebMethod()>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Function SetTavoli(ByVal data As String) As String
Dim con As MySqlConnection = New MySqlConnection
con.ConnectionString = "CONNSTRING"
DeleteSTB(con)
Dim strSql As String = "QUERY"
Dim dtb As New DataTable
con.Open()
Dim sqlCmd As New MySqlCommand(strSql, con)
Dim sqlDad As New MySqlDataAdapter(sqlCmd)
sqlDad.Fill(dtb)
con.Dispose()
dtb.Columns(0).ColumnName = "data"
dtb.Columns(1).ColumnName = "orain"
dtb.Columns(2).ColumnName = "oraout"
dtb.Columns(3).ColumnName = "numtav"
dtb.Columns(4).ColumnName = "numcop"
dtb.Columns(5).ColumnName = "email"
dtb.Columns(6).ColumnName = "tel"
dtb.Columns(7).ColumnName = "note"
dtb.Columns(8).ColumnName = "nome"
dtb.Columns(9).ColumnName = "id"
dtb.Columns(10).ColumnName = "stato"
Return Json(dtb)
End Function
So i was wondering what i'm doing wrong and how i could fix that issue still by using long polling...
To the website there will be connected lot of users with their own account and will be accessing their own databases..

Why sub json contains backslashes

I need To Build json of the following structure:
[{
Id: M1
Name: Menu1
Checked: True
Children:[
{Id: I1 , Name: Item1 , Checked: true, view:true , write:true},
{Id: I2 , Name: Item2 , Checked: true, view:true , write:true},
.. etc
]
},
{
Id: M2
Name: Menu2
Checked: True
Children:[
{Id: I1 , Name: Item1 , Checked: true, view:true , write:true},
{Id: I2 , Name: Item2 , Checked: true, view:true , write:true},
.. etc
]
} , etc..
]
I'm Using Vb.Net , SQl Server To get the menus and Items (objects) from the database and convert the data to json string using this code:
'Get Menus
Dim menus = DataFactory.Instance.GetMenusAndObjects(connectionString)
'Create JSON String
Dim jsonSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim json As String = "["
For Each m In menus
Dim children As String = "["
Dim menu_checked As Boolean = True
For Each obj In m.Objects
Dim checked As Boolean = True
Dim view As Boolean = True
Dim write As Boolean = True
Dim link = DataFactory.Instance.GetProfileObjectLink(connectionString, profile_code, obj.ObjectCode)
If IsNothing(link) Then
view = False
write = False
checked = False
menu_checked = False
Else
If link.AllowToView.Equals("N") Then
view = False
menu_checked = False
End If
If link.AllowToModify.Equals("N") Then
write = False
menu_checked = False
End If
End If
children &= jsonSerializer.Serialize(New With {Key .Id = obj.ObjectCode,
.Name = obj.ObjectDesc,
.Checked = checked,
.View = view,
.Write = write}) & ","
Next
children &= "]"
json &= jsonSerializer.Serialize(New With {Key .Id = m.MenuCode,
.Name = m.MenuName,
.Checked = menu_checked,
.Children = children}) & ","
Next
If json.Length > 1 Then
json = json.Substring(0, json.Length - 1)
End If
json &= "]"
A Sample of the Resulted Json string in vb.Net:
[{"Id":"APPLN","Name":"Application","Checked":false,"Children":"
[{\"Id\":\"CUSTOMER_SCR\",\"Name\":\"62- Clients/
Customers\",\"Checked\":true,\"View\":false,\"Write\":false},
{\"Id\":\"EMP_SCR\",\"Name\":\"10- Employee
Manager\",\"Checked\":true,\"View\":true,\"Write\":true},]"}
,]"}
Why Backslashes are added only to the json on 'Children' Property? Do you think that the double Serialization for the children parameter is causing the problem? and if that's is the real reason how can I concatenate children jsons to the main json strings?
I pushed Each Children into a List Of Object then I converted the list to Array after that I serialized the main json, The Code:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Script.Serialization
Public Class GetMenusAndObjects
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
'Get parameters
Dim profile_code = context.Request("profile_code")
Dim connectionString As String = UserIdentity.ClientConfig.ConnectionString
'Get Profiles
Dim menus = DataFactory.Instance.GetMenusAndObjects(connectionString)
'Create JSON String
Dim jsonSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim json As String = "["
For Each m In menus
' Dim children As String = "["
Dim children = New List(Of Object)
Dim menu_checked As Boolean = True
For Each obj In m.Objects
Dim checked As Boolean = True
Dim view As Boolean = True
Dim write As Boolean = True
Dim link = DataFactory.Instance.GetProfileObjectLink(connectionString, profile_code, obj.ObjectCode)
If IsNothing(link) Then
view = False
write = False
checked = False
menu_checked = False
Else
If link.AllowToView.Equals("N") Then
view = False
menu_checked = False
End If
If link.AllowToModify.Equals("N") Then
write = False
menu_checked = False
End If
End If
children.Add(New With {.Id = obj.ObjectCode,
.Name = obj.ObjectDesc,
.Checked = checked,
.View = view,
.Write = write
})
'children &= jsonSerializer.Serialize(New With {Key .Id = obj.ObjectCode,
' .Name = obj.ObjectDesc,
' .Checked = checked,
' .View = view,
' .Write = write}) & ","
Next
'children &= "]"
json &= jsonSerializer.Serialize(New With {Key .Id = m.MenuCode,
.Name = m.MenuName,
.Checked = menu_checked,
.Children = children.ToArray()}) & ","
Next
If json.Length > 1 Then
json = json.Substring(0, json.Length - 1)
End If
json &= "]"
'Return JSON in response
context.Response.Write(json)
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Fullcalendar in ASP.NET and JSON response

I am fetching my events with webservice:
Public Function webGetCalendarEvents(ByVal startDate As String, ByVal endDate As String) As String
Dim sDate As DateTime = ToUnixTimeSpan(startDate)
Dim eDate As DateTime = ToUnixTimeSpan(endDate)
Dim DS As DataSet = DBStoredProcedures.GetEventsCalendarJSON(95, sDate, eDate)
DS.Tables(0).TableName = "events"
Dim dataTable As DataTable = DS.Tables(0)
Dim jsonEvents As String = Newtonsoft.Json.JsonConvert.SerializeObject(dataTable)
Return jsonEvents
The json response is like:
[
{
"id":589311,
"title":"My Title",
"priority":"",
"start":"2011-09-19T08:00",
"end":"2011-09-26T16:00",
"allDay":"false",
"editable":"true",
"EOSid":0
}
]
The problem is, that all my events are shown as allDay events. It seems like "false" value of "allDay" is not recognized.
I am evaluating the response inside fullcalendar.js file (version 1.5.2., line around 981):
success: function (events) {
events = (typeof events.d) == 'string' ? eval('(' + events.d + ')') : events.d || [];
How can I render events to accept "allDay" parameter?
SOLVED:
I changed my SQL procedure where I was generating "allDay" parameter. I changed from:
CASE WHEN EventTypeID=3 THEN 'false' ELSE 'true' END as allDay
to:
CASE WHEN EventTypeID=3 THEN CAST(0 as BIT) ELSE CAST(1 as BIT) END as allDay
This gave me JSON response:
{"allDay": false}
instead of:
{"allDay": "false"}