How To Fix Circular Reference Error When Dealing With Json

前端 未结 2 697
离开以前
离开以前 2020-12-03 04:53

This question is a part of my original post here Get Data Into Extjs GridPanel

Below is my Controller that reads data from sql db and then I am trying to encode the

相关标签:
2条回答
  • 2020-12-03 05:35

    I use the following tool for serializing and deserializing JSON:

    http://james.newtonking.com/pages/json-net.aspx

    It's very easy to use and very lightweight.

    While serializing we use this option:

    JsonConvert.SerializeObject(myObject, Formatting.Indented, 
                                new JsonSerializerSettings { 
                                       ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
                                })
    

    It ignores circular references.

    Also json.net from newtonking is extremely fast.

    The other options is to use DTO's and map them via Automapper as mentioned by Diver.

    Edit: I suspect your store is wrong:

    var store = Ext.create('Ext.data.JsonStore', {      
            storeId: 'myData',
            reader: new Ext.data.JsonReader({
                root: 'myTable',
                fields: [{ name: 'Q1', type: 'int' },
                         { name: 'Q2', type: 'int' },
                         { name: 'Q3', type: 'int' },
                         { name: 'Q4', type: 'int' },
                         { name: 'Q5', type: 'int' },
                         { name: 'Improvements', type: 'string' },
                         { name: 'Comments', type: 'string'}]
            }),
    
            proxy: {
                 type: 'json',
                url: 'GridView/writeRecord'
            }    
    });  
    
    0 讨论(0)
  • 2020-12-03 05:43

    It's because something inside CultureInfo has a reference to itself (this type) and in process of converting to JSON it fails. To avoid this situation, you should use ViewModels (return to client only information that is needed). You can read more here http://blogs.msdn.com/b/dphill/archive/2009/01/31/the-viewmodel-pattern.aspx

    In your situation you shoud create ViewModels for your data, convert your data to these data types and return them converted to JSON. For the purpose of converting from Model to ViewModel consider using AutoMapper http://automapper.codeplex.com/ or some similar tool.

    0 讨论(0)
提交回复
热议问题