JSON文件数组被解释为字符串

时间:2017-12-01 09:31:35

标签: c# asp.net json

我正在用C#恢复Ajax数据,所以我创建了一个具有以下格式的JSON文件:

{
      "type": 2,
      "body": "Hello",
      "time": 120000,
      "ip": [
        "[\"192.168.10.1-192.168.10.254\",\"192.168.11.1-192.168.11.254\",\"192.168.12.1-192.168.11.20\",\"192.168.1.5-192.168.1.50\"]"
      ],
      "hash": "6e42b725e351576d123ba7d4fc1b48863e4485821e0edb73abb8801a09a99bc7",
      "exclue": "127.0.0.1 "
}

与此:

public void exportConf(int type, string body, int time, string[] SendIp, string lstIp)
{
    StringBuilder Sb = new StringBuilder();
    byte[] bytes = Encoding.UTF8.GetBytes("test");
    SHA256 crypt =  SHA256.Create();
    byte[] hashBytes = crypt.ComputeHash(bytes);
    foreach (byte a in hashBytes)
    {
        Sb.Append(a.ToString("x2"));
    }
    JObject data = new JObject(
        new JProperty("type", type),
        new JProperty("body", body),
        new JProperty("time", (time*60*1000)),
        new JProperty("ip", JArray.FromObject(SendIp)),
        new JProperty("hash", Sb.ToString()),
        new JProperty("exclue", lstIp)
        );

    System.IO.File.WriteAllText(System.IO.Path.GetTempPath()+"xyz.json", data.ToString());
}

我从我的JS中调用这个函数:

$('.send').click(function () {
var subnet = [];
$('table tbody tr td input[type=checkbox]').each(function () {
    if ($(this).is(':checked')) {
        subnet.push($(this).val());
    }
});
idType = $(".slct-type select :selected").val();
body = $('.zoneEdit textarea').val();
time = $('input[name=timeout]').val();
lstIp = $('.zoneIp textarea').val();
if (subnet.length > 0) {
    $.ajax({
        url: '/Scripts/exportConf',
        type: "POST",
        data: { type: idType, body: body, time: time, Sendip: JSON.stringify(subnet), lstIp: lstIp },
        dataType: "json",
        success: function (data) {
            for (i = 0; i < data.length; i++) {
                if (data[i].id == idType) {
                } else {

                }
            }

        }
    });
} else {
    alertbox('danger', 'Error', 2000);
}

});

当我像这样解析我的JSON文件时:

        if (File.Exists(Path.GetTempPath() + "xyz.json"))
        {
            JObject data = JObject.Parse(File.ReadAllText(System.IO.Path.GetTempPath() + "xyz.json"));
            Console.Write(data["ip"]);

        }

data ['IP']通常应该是一个数组,但是当我做数据['IP'] [0]时,我得到了这个:

["192.168.10.1-192.168.10.254","192.168.11.1-192.168.11.254","192.168.12.1-192.168.11.20","192.168.1.5-192.168.1.50"]

IP不被视为数组,但作为单个字符串,我不知道为什么。你有解决方案吗?

编辑:我找到了解决方案,你必须“传统”地了解真相。

http://api.jquery.com/jQuery.param/

Thx!

    $('.send').click(function () {
    var subnet = [];
    $('table tbody tr td input[type=checkbox]').each(function () {
        if ($(this).is(':checked')) {
            subnet.push($(this).val());
        }
    });
    idType = $(".slct-type select :selected").val();
    body = $('.zoneEdit textarea').val();
    time = $('input[name=timeout]').val();
    lstIp = $('.zoneIp textarea').val();
    if (subnet.length > 0) {
        $.ajax({
            url: '/Scripts/exportConf',
            type: "POST",
            data: { type: idType, body: body, time: time, Sendip: subnet, lstIp: lstIp },
            traditional : true,
            dataType: "json",
            success: function (data) {
                for (i = 0; i < data.length; i++) {
                    if (data[i].id == idType) {
                    } else {

                    }
                }

            }
        });
    } else {
        alertbox('danger', 'Merci de selectionner un réseau', 2000);
    }
});

2 个答案:

答案 0 :(得分:1)

您的代码不会生成嵌套数组,它会生成一个包含单个字符串值的数组。

如果您创建了DTO并直​​接将其序列化,那么生成JSON字符串会更容易很多。它还可以避免生成这么多临时对象:

class MyDTO
{
    public int type{get;set;}
    public string body {get;set;}
    public int time {get;set;}
    public string[][] ip{get;set;}
    public string hash {get;set;}
    public string exclude {get;set;}
}

void Main()
{
    var myDto=new MyDTO{
        type=2,
        body="Hello",
        time=120000,
        ip=new []{
            new []{
                "192.168.10.1-192.168.10.254",
                "192.168.11.1-192.168.11.254",
                "192.168.12.1-192.168.11.20",
                "192.168.1.5-192.168.1.50"
            }
        },
        hash="6e42b725e351576d123ba7d4fc1b48863e4485821e0edb73abb8801a09a99bc7",
        exclude = "127.0.0.1"
    };

    var json=JsonConvert.SerializeObject(myDto,Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(json);
}

结果是:

{
  "type": 2,
  "body": "Hello",
  "time": 120000,
  "ip": [
    [
      "192.168.10.1-192.168.10.254",
      "192.168.11.1-192.168.11.254",
      "192.168.12.1-192.168.11.20",
      "192.168.1.5-192.168.1.50"
    ]
  ],
  "hash": "6e42b725e351576d123ba7d4fc1b48863e4485821e0edb73abb8801a09a99bc7",
  "exclude": "127.0.0.1"
}

更新1

如果您不想使用DTO,可以使用匿名类型。结果将是相同的:

    var myDto=new {
        type=2,
        body="Hello",
        time=120000,
        ip=new []{
            new []{
                "192.168.10.1-192.168.10.254",
                "192.168.11.1-192.168.11.254",
                "192.168.12.1-192.168.11.20",
                "192.168.1.5-192.168.1.50"
            }
        },
        hash="6e42b725e351576d123ba7d4fc1b48863e4485821e0edb73abb8801a09a99bc7",
        exclude = "127.0.0.1"
    };

您可以使用JsonConvert.DeserializeObject

将字符串反序列化到DTO
var dto=JsonConvert.DeserializeObject<MyDTO>(json);
var fistRange=dto.ip[0][0];

或者您可以反序列化为动态对象:

    dynamic result=JsonConvert.DeserializeObject<dynamic>(json);
    Console.WriteLine(result.ip[0][0]);

在这两种情况下,结果都是:

192.168.10.1-192.168.10.254

更新2

原始代码会产生问题中显示的结果。它生成一个包含IP范围的字符串数组属性。这段代码:

    var sendIPs =new []{
                "192.168.10.1-192.168.10.254",
                "192.168.11.1-192.168.11.254",
                "192.168.12.1-192.168.11.20",
                "192.168.1.5-192.168.1.50"
            };
    var hashString = "6e42b725e351576d123ba7d4fc1b48863e4485821e0edb73abb8801a09a99bc7";                
    JObject data = new JObject(
        new JProperty("type", 2),
        new JProperty("body", "Hello"),
        new JProperty("time", 12000),
        new JProperty("ip", JArray.FromObject(sendIPs)),
        new JProperty("hash", hashString),
        new JProperty("exclue", "127.0.0.1")
    );
    var json = data.ToString();

返回

{
  "type": 2,
  "body": "Hello",
  "time": 12000,
  "ip": [
    "192.168.10.1-192.168.10.254",
    "192.168.11.1-192.168.11.254",
    "192.168.12.1-192.168.11.20",
    "192.168.1.5-192.168.1.50"
  ],
  "hash": "6e42b725e351576d123ba7d4fc1b48863e4485821e0edb73abb8801a09a99bc7",
  "exclue": "127.0.0.1"
}

也许SendIP包含已经序列化的数组字符串?

答案 1 :(得分:0)

也许它应该是;

new JProperty("ip", JArray.FromObject(SendIp[0]))