0

I have a dynamic function to generate table data to JSON which kinda works, now I try to add it to a list in .NET however I can't get this right past few days, anybody knows what I do wrong?

the output is like this:

[{"itemsSerialized":"{\"id\":1,\"name\":\"Medical 1\",\"city\":\"Kiev\",\"instituteTypeId\":0}"},{"itemsSerialized":"{\"id\":2,\"name\":\"Medical 2\",\"city\":\"Kherson\",\"instituteTypeId\":0}"}]

which should be without the "itemsSerialized":", I understand where it comes from, but dont understand why a object declaration suddenly shows up in my JSON string

my C# code:

Object itemsSerialized = "";
        foreach (DataRow r in _data.Rows)
        {
            DynamicClass dynamicClass = new DynamicClass();
            dyna.ConvertRowToCustomer(r, out dynamicClass);
            DynamicClassList.Add(dynamicClass);
            var iSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            itemsSerialized = JsonConvert.SerializeObject(dynamicClass.Property.properties);
            Object itemsSerialized2 = JsonConvert.DeserializeObject(xJSON);
            Gridist.Add(new { itemsSerialized });
        }

with jQuery I have this to load the data into the jQGrid:

$.ajax({
        type: "POST",
        contentType: "application/json",
        url: "dataServices/objects.asmx/InvokeData",
        data: "{ 'q': 'med&1'}",
        dataType: 'json',
        success: function (result) {
            var str = result.d;
            alert(result.d);
            $("#jqGrid_2")[0].addJSONData(result.d);
        }
    });

The return I have now as:

{"id":1,"name":"Medical 1","city":"Kiev","instituteTypeId":0},{"id":2,"name":"Medical 2","city":"Kherson","instituteTypeId":0}

UPDATE INTERNAL AJAX VERSION:

  mtype: 'POST',
                contentType: "application/json",
                url: "dataServices/objects.asmx/InvokeData",
                ajaxGridOptions: {
                    contentType: 'application/json; charset=utf-8'
                },
                postData: JSON.stringify({q: "med&1"}),
                loadonce: true,
                dataType: 'json',
                jsonReader: {
                    root: function (obj) {
                        alert(obj.d);
                        return obj.d;
                    },
                    page: "",
                    total: "",
                    records: function (obj) {
                        return obj.d.length;
                    },
                },
                gridview: true,
                loadError: function (xhr, status, error) {
                    alert('load error: ' + error);
                },

And is being written away in the first column from first and only row....

What I do wrong and how I get the itemsSerialized out

Jaap Terlouw
  • 125
  • 1
  • 15

1 Answers1

0

First of all the server response

{
    "id": 1,
    "name": "Medical 1",
    "city": "Kiev",
    "instituteTypeId": 0
},
{
    "id": 2,
    "name": "Medical 2",
    "city": "Kherson",
    "instituteTypeId": 0
}

is wrong. Correct data should be array of items like

[
    {
        "id": 1,
        "name": "Medical 1",
        "city": "Kiev",
        "instituteTypeId": 0
    },
    {
        "id": 2,
        "name": "Medical 2",
        "city": "Kherson",
        "instituteTypeId": 0
    }
]

Another JSON response which you posted contains two problems. 1) "itemsSerialized":" prefix 2) the value of all items are strings

[
    {
        "itemsSerialized": "{\"id\":1,\"name\":\"Medical 1\",\"city\":\"Kiev\",\"instituteTypeId\":0}"
    },
    {
        "itemsSerialized": "{\"id\":2,\"name\":\"Medical 2\",\"city\":\"Kherson\",\"instituteTypeId\":0}"
    }
]

The reason of the first problem is the usage of

Gridist.Add(new { itemsSerialized });

instead of

Gridist.Add(itemsSerialized);

The reason of the second problem is unneeded usage of JsonConvert.SerializeObject. What you should do is something like

Gridist.Add(dynamicClass.Property.properties);

instead of

itemsSerialized = JsonConvert.SerializeObject(dynamicClass.Property.properties);
Gridist.Add(new { itemsSerialized });
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Hello Oleg, trying it now – Jaap Terlouw Oct 11 '13 at 16:08
  • Pfffh, did not see this comming, staring at this for 2 days :S Many thanks for ur comments – Jaap Terlouw Oct 11 '13 at 16:10
  • @JaapTerlouw: You are welcome! I recommend you additionally to change your code a little. You should remove usage of `addJSONData` and use `datatype: 'json'` with `jsonReader` which contains `root: function (obj) { return obj.d; }`. See [the answer](http://stackoverflow.com/a/9646371/315935), [this one](http://stackoverflow.com/a/12186431/315935) and many other. Additionally you can add `loadonce: true` option. – Oleg Oct 11 '13 at 16:18
  • I have ajax outside of the jqGrid can I add this within the ajax? – Jaap Terlouw Oct 11 '13 at 16:21
  • $("#jqGrid_2")[0].addJSONData(result.d); this should be $("#jqGrid_2")[0].(result.d);? – Jaap Terlouw Oct 11 '13 at 16:23
  • $("#jqGrid_2").result.d; no results ((( – Jaap Terlouw Oct 11 '13 at 16:25
  • @JaapTerlouw: jqGrid should better make the Ajax call for you. See referenced answers. Usage of `addJSONData` is really bad. It's low level method. If you use `datatype: 'json'` with `url` jqGrid can make Ajax call for you. You can combine such way with `loadonce: true` and get advantages like local sorting, paging and filtering/searching of data. – Oleg Oct 11 '13 at 16:27
  • @JaapTerlouw: I don't understand what you mean with the code `$("#jqGrid_2").result.d` or `$("#jqGrid_2")[0].(result.d);`. It's wrong and it's not what I suggested you. – Oleg Oct 11 '13 at 16:28
  • Placing the ajax inside the jqGrid makes the connection to the asmx server however does not load the data into the grid { url: $.ajax({ type: "POST", contentType: "application/json", url: "dataServices/objects.asmx/InvokeData", data: "{ 'q': 'med&1'}", dataType: 'json', success: function (result) { //var str = result.d; //alert(result.d); //$("#jqGrid_2")[0].addJSONData(str); } }), – Jaap Terlouw Oct 11 '13 at 16:33
  • The jqGrid need to load data into the grid, I have not implemented yet the rows, pages, ect so I assume the jsonReader does not work yet – Jaap Terlouw Oct 11 '13 at 16:36
  • Changed it confirm your advise.... no data see up, connects still to the WebMethod – Jaap Terlouw Oct 11 '13 at 16:47
  • @JaapTerlouw: You should careful in the usage of jqGrid options. `url: $.ajax({... })` is **absolutely wrong**. No direct usage of `$.ajax` should be in your code. You should use `url: "dataServices/objects.asmx/InvokeData"` *as parameter of jqGrid*. Additionally you should use `mtype: 'POST'`, `datatype: 'json'`, `ajaxGridOptions: { contentType: 'application/json; charset=utf-8' }`, postData: `JSON.stringify({q: "med&1"});` and so on. – Oleg Oct 11 '13 at 16:49
  • Hi Oleg, I have adjusted it all call to server is being made however returns no results in the grid but get a strange error: load error: Error: Invalid XML: {"d":[{"id":1,"name":"Medical 1","city":"Kiev","instituteTypeId":0},{"id":2,"name":"Medical 2","city":"Kherson","instituteTypeId":0}]}, Updated the jqGrid code – Jaap Terlouw Oct 11 '13 at 17:03
  • @JaapTerlouw: It means that you either forgot to include `datatype: 'json'` option in jqGrid and default option `datatype: 'xml'` was used or you forgot to include `ajaxGridOptions: { contentType: 'application/json; charset=utf-8' }`. It's better that you opens new question and include JavaScript code which you use now and the server response produced by your server. – Oleg Oct 11 '13 at 17:07
  • @JaapTerlouw: The option should be `datatype: 'json'` and not `dataType: 'json'` – Oleg Oct 11 '13 at 17:11
  • http://stackoverflow.com/questions/19323792/jqgrid-does-not-load-and-with-error-that-its-invalid-xml-however-data-is-json – Jaap Terlouw Oct 11 '13 at 17:20