返回没有大写字母的json变量

时间:2017-12-18 16:27:16

标签: json go

我是将应用程序转换为Go的新用户。我有类似以下的工作:

using System;
using System.Collections.Generic;
using System.Linq;
using COCApp;
using Foundation;
using UIKit;

namespace COCApp.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the 
    // User Interface of the application, as well as listening (and optionally responding) to 
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        //
        // This method is invoked when the application has loaded and is ready to run. In this 
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
    }
}

问题是旧版本没有在返回的json变量上使用大写字母。

我希望前端看到type Network struct { Ssid string Security string Bitrate string } func Scan(w http.ResponseWriter, r *http.Request) { output := runcmd(scripts+"scan.sh", true) bytes := []byte(output) var networks []Network json.Unmarshal(bytes, &networks) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(networks) } 而不是ssid。如果我将结构中的属性设置为小写,则代码不再有效,因为它们成为未导出的变量。

2 个答案:

答案 0 :(得分:4)

如果结构中的字段名称与json字段名称不匹配,则可以使用字段标记。 例如:

Ssid string `json:"myOtherFieldName"`

请阅读json docs了解详情。

答案 1 :(得分:1)

这个工具非常方便学习:

https://mholt.github.io/json-to-go/

给它你希望它推荐golang的JSON示例。

e.g。 JSON

{
   "ssid": "some very long ssid",
   "security": "big secret",
   "bitrate": 1024
}

会建议golang:

type AutoGenerated struct {
    Ssid     string `json:"ssid"`
    Security string `json:"security"`
    Bitrate  int    `json:"bitrate"`
}

现在您可以将AutogGenerated, Ssid, Security, Bitrate更改为您想要的任何内容。