简体   繁体   English

在C#中转换JSON对象

[英]Converting JSON object in C#

The problem is that is not printing anything. 问题是没有打印任何东西。 I have list of surnames in aspx.cs, and I am trying to parse in JSON object so I can use them in aspx. 我在aspx.cs中有一个姓氏列表,我正在尝试在JSON对象中解析,以便可以在aspx中使用它们。 I think the problem is in the script because when I Response.Write('jsonString') it prints in a correctly JsonFormat . 我认为问题出在脚本中,因为当我Response.Write('jsonString')它将以正确的JsonFormat打印。

WebForm1.aspx.cs WebForm1.aspx.cs

I have List of Surnames 我有姓氏清单

public List<String> surname= new List<String>();

and a method that is making the list to jsonString 以及将列表添加到jsonString

 public string getJson() {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            string jsonString = javaScriptSerializer.Serialize(surname);
            return jsonString;
        }  

WebForm1.aspx WebForm1.aspx

this is the script 
 <script>
        $(function () {
            $.ajax({
                url: "WebForm1.aspx/getJson",
                dataType: "json",
                success: function (data) {
                    $("#Label2").append(data + " ");
                }
            });
        });

    </script>

and web contorl 和网络控制

 <asp:Label ID="Label2" runat="server" Text=""></asp:Label>

have tried following line ? 是否尝试过以下路线?

in asp.net you have to get client id and than set your data 在asp.net中,您必须获取客户端ID,然后设置数据

$('#<%=Label2.ClientID%>').html(data)

Your WebMethod should be like: 您的WebMethod应该像这样:

[WebMethod]
public static List<string> getJson()
{
      List<String> surname = YourFunctionForSurnames();
      return surname;
}

Your JavaScript 您的JavaScript

$(function () {
        $.ajax({
            type:'post',
            url: "WebForm1.aspx/getJson",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                console.log(data);
                $("#Label2").append(data.d + " ");                    

            }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest + '  ' +textStatus + '  ' + errorThrown);
            }
        });
    });

I testing and working on my machine. 我在机器上进行测试和工作。

我认为您需要在js中使用对象之前添加JSON序列化,例如JSON.parse(jsonString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM