如何在不输出某些值的引号的情况下序列化JSON

时间:2016-03-29 19:43:01

标签: json asp.net-mvc serialization highcharts json.net

问题的简短版本。在某些情况下,我不想在字符串JSon值上引用:

Color = Highcharts.getOptions()。colors [0]

而不是:

Color =“Highcharts.getOptions()。colors [0]”

+++++++++++++++++++++++++++++++++++++++

详细信息....我有一个工作代码,它是我为客户端生成HighCharts.com图形的所有Json的控制器(作为概念证明)的模型。

1

客户代码(有效)

@{
    ViewBag.Title = "View";
}

<h2>High Charts Proof of Concept</h2>


<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

@section Scripts {
    <script type="text/javascript">
    $(function() {
        fetchSampleChart1();

        function fetchSampleChart1() {
        $.ajax({
            url: '/Test1/SampleChart1/',
            type: 'GET',
            //data: '?',
            //data: 'adminEntityID=' + adminEntity + '&fieldName=' + fieldName + '&fieldValue=' + fieldValue + '&outletID=' + outlet,
            complete: function (data, textStatus, xhr) {
                console.log(data.responseText);
                var strGraphData = $.parseJSON(data.responseText);
                if (strGraphData.length == 0) {
                //GraphEmptyDisplay(parmChartId, msg);
                console.log("!!!!GRAPH DATA EMPTY!!!!");
                return '';
                }
                $("#container").highcharts(strGraphData);
            },
            error:function(xhr, textStatus, errorThrown) {
            //Inject a default error message to the modal target. 
        }
        });
    }

    });
    </script>

    <script type="text/javascript" src="/scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="https://code.highcharts.com/highcharts.js"></script>
    <script type="text/javascript" src="https://code.highcharts.com/modules/exporting.js"></script>

}

2

它调用的控制器动作。除了它在所有输出上发出引号,我只想在大部分输出中使用它。

    [HttpGet]
    public ContentResult SampleChart1()
    {
        var sc = new HighChartGraph
        {
            Title = new Title() {Text = "Combination Chart"},
            XAxis = new XAxis() {Categories = new string[] {"Apples", "Oranges", "Pears", "Banannas", "Plums"}},
            Center = "[100,80]",
            Size = 100,
            ShowInLegend = false,
            DataLabels = new dataLabels {Enabled = false},
            Labels = new Labels
            {
                Items = new Items
                {
                    Html = "Total Fruit consumption",
                    Style =
                        new Style()
                        {
                            Left = "50px",
                            Top = "18px",
                            //Color = "(Highcharts.theme && Highcharts.theme.textColor) || 'black'"
                            Color="yellow"
                        }
                }
            },
            Series = new List<GraphSeries>
            {
                new GraphSeries
                {
                    GraphType = "column",
                    Name = "Jane",
                    DataSimple = new decimal[] {3, 2, 1, 3, 4}
                },
                new GraphSeries
                {
                    GraphType = "column",
                    Name = "John",
                    DataSimple = new decimal[] {2, 3, 5, 7, 6}
                },
                new GraphSeries
                {
                    GraphType = "column",
                    Name = "Joe",
                    DataSimple = new decimal[] {4, 3, 3, 9, 0}
                },
                new GraphSeries
                {
                    GraphType = "spline",
                    Name = "Average",
                    DataSimple = new decimal[] {3, 2.67m, 3, 6.33m, 3.33m},
                    Marker =
                        new marker
                        {
                            LineWidth = 2,
                            LineColor = "Highcharts.getOptions().colors[3]",
                            //LineColor="Black",
                            FillColor = "white"
                        }
                },
                new GraphSeries
                {
                    GraphType = "pie",
                    Name = "Total Consumption",
                    DataExtended = new List<Data>
                    {
                        new Data {Name = "Jane", Y = 13, Color = "Highcharts.getOptions().colors[0]"},
                        //new data {Name = "Jane", Y = 13, Color = "Red"},
                        new Data {Name = "John", Y = 23, Color = "Highcharts.getOptions().colors[1]"},
                        //new data {Name = "John", Y = 23, Color = "Black"},
                        new Data {Name = "Joe", Y = 19,  Color = "Highcharts.getOptions().colors[2]"}
                        //new data {Name = "Joe", Y = 19, Color = "Blue"},
                    }
                }
            }
        };
        //var j=new JavaScriptSerializer().Serialize(sc); // .NET Serialization will not use  [JsonProperty()] attributes
        var j = JsonConvert.SerializeObject(sc); // Newtonsoft Serialization WILL USE [JsonProperty()] attributes
        //return Json(sc,JsonRequestBehavior.AllowGet); // cannot use it will not use our NewtonSoft serialization
        return Content(j, "application/json");
    }

3 Model它调用get get:

    public class HighChartGraph
    {
    [JsonProperty(PropertyName = "title")]
    public Title Title;

    [JsonProperty(PropertyName = "xAxis")]
    public XAxis XAxis;

    [JsonProperty(PropertyName = "labels")]
    public Labels Labels;

    [JsonProperty(PropertyName = "center")]
    public string Center;

    [JsonProperty(PropertyName = "size")]
    public int Size;

    [JsonProperty(PropertyName = "showInLegend")]
    public bool ShowInLegend;

    [JsonProperty(PropertyName = "dataLabels")]
    public dataLabels DataLabels;

    [JsonProperty(PropertyName = "series")]
    public List<GraphSeries> Series;
    }

    public class Title
    {
    [JsonProperty(PropertyName = "text")]
    public string Text;
    }

    public class XAxis
    {
    [JsonProperty(PropertyName = "categories")]
    public string[] Categories;
    }

    public class Labels
    {
    [JsonProperty(PropertyName = "items")]
    public Items Items;
    }

    public class Items
    {
    [JsonProperty(PropertyName = "html")]
    public string Html;
    [JsonProperty(PropertyName = "style")]
    public Style Style;
    }

    public class Style
    {
    [JsonProperty(PropertyName = "left")]
    public string Left;

    [JsonProperty(PropertyName = "top")]
    public string Top;

    [JsonProperty(PropertyName = "color")]
    public string Color;
    }

    public class GraphSeries
    {
    private string _GraphType;

    [JsonProperty(PropertyName = "type")]
    public string GraphType
    {
        get { return _GraphType; }

        set { _GraphType = value; }

    }
    [JsonProperty(PropertyName = "name")]
    public string Name;

    [JsonProperty(PropertyName = "marker")]
    public marker Marker;

    [JsonProperty(PropertyName = "data")]
    public object Data
    {
        get
        {
        if (DataSimple != null) return DataSimple;
        if(DataExtended !=null) return DataExtended;
        return null;
        }
    }
    [NonSerialized][ScriptIgnore]
    public decimal[] DataSimple = null;

    [NonSerialized][ScriptIgnore]
    public List<Data> DataExtended = null;
    }


 public class Data
    {
    [JsonProperty(PropertyName = "name")]
    public string Name;

    [JsonProperty(PropertyName = "y")]
    public long Y;

    [JsonProperty(PropertyName = "color")]
    public string Color;
    }

    public class dataLabels
    {
    [JsonProperty(PropertyName = "enabled")]
    public bool Enabled;
    }

    public class marker
    {
    [JsonProperty(PropertyName = "linewidth")]
    public int LineWidth;

    [JsonProperty(PropertyName = "linecolor")]
    public string LineColor;

    [JsonProperty(PropertyName = "fillcolor")]
    public string FillColor;
    }

4这里的参考点是HighCharts图,我创建了模型和示例代码:

http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/combo/

2 个答案:

答案 0 :(得分:2)

HighCharts不是采用JSON而是实际的javascript对象。这就是为什么他们能够拥有可执行内容的原因。出于安全原因,JSON非常具体是非可执行的,仅限数据。

你在这里有几个选择:

  • 使用JSON作为交换格式,但是具有通过JSON旋转的客户端函数,如果它包含允许的可执行函数,则注意它,eval()&#39;它会将值重写回属性。
  • 编写您自己的JSONish生成器,该生成器反映在对象树上,并构建一个可执行的javascript对象与JSON
  • 进入JSON.NET并创建一个不带引号呈现的ExecutableString类型。看起来你可以按照https://stackoverflow.com/a/21766191/8037的方式制作一个JsonConverter来做到这一点。喜欢那个JsonConverter,除了调用writer.WriteRaw或writer.WriteRawValue来写出js。

我不必提及,通过这样做,你最终会遇到许多安全功能。评估从外部源接收的任何代码可能是危险的。也就是说,如果该功能是概念证明,并且它只是联系您控制的服务器并且不能以不同的方式注入,那么您应该非常安全。

答案 1 :(得分:0)

我只是更新public class Data,以便不使用ColorLineColor属性的字符串,而是使用某种枚举:

new Data {Name = "Joe", Y = 19,  Color = HighchartsCcolor2 }

然后在客户端上,循环浏览data.responseText并启用.Color属性。你可以根据枚举值使用你想要的值。

这将允许您返回有效的JSON并按照您希望的方式处理它。