如何在Go中显示来自API的JSON响应?

时间:2020-09-06 01:20:02

标签: json go

我正在调用一个小的API,该API会返回一个带有Todo对象的JSON响应。如何在Go Web服务器上显示它?现在,所有显示的都是我硬编码的“ Todo”。如何用API JSON响应代替?

代码如下:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
)

// Todo Structure
type Todo struct {
    userID    int
    id        int
    title     string
    completed bool
}

func main() {
    http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "<h1>Todo</h1>")
    })

    response, err := http.Get("http://jsonplaceholder.typicode.com/todos/1")

    if err != nil {
        fmt.Print(err.Error())
        os.Exit(1)
    }

    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(responseData))

    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

1 个答案:

答案 0 :(得分:0)

您必须编写一个委派的函数来从外部网站检索数据。比起使用public class NowyTrening extends AppCompatActivity { SilkaDataBaseHelper SilkaDataBaseHelper; Cursor cursor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nowy_trening); TextView kgg = (TextView) findViewById(R.id.kg1); TextView uno = (TextView) findViewById(R.id.uno1); TextView dos = (TextView) findViewById(R.id.dos1); TextView tres = (TextView) findViewById(R.id.tres1); SilkaDataBaseHelper = new SilkaDataBaseHelper(this); //SilkaDataBaseHelper.zapis(60,12,11,12); //COFANIE NA PASKU AKCJI getSupportActionBar().setDisplayHomeAsUpEnabled(true); cursor = SilkaDataBaseHelper.daj3(); while(cursor.moveToNext()) { int kg = cursor.getInt(0); int jed = cursor.getInt(1); int dwa = cursor.getInt(2); int trz= cursor.getInt(3); System.out.println(jed+" "+dwa); kgg.setText(String.valueOf(kg)); uno.setText(String.valueOf(jed)); dos.setText(String.valueOf(dwa)); tres.setText(String.valueOf(trz)); break; } } public void ZapiszOnClick(View view) { SilkaDataBaseHelper db = new SilkaDataBaseHelper(this); EditText e1 = (EditText)findViewById(R.id.e1); EditText e2 = (EditText)findViewById(R.id.e2); EditText e3 = (EditText)findViewById(R.id.e3); String ww1=e1.getText().toString(); String ww2=e2.getText().toString(); String ww3=e3.getText().toString(); int kg; System.out.println(ww1); int i=Integer.parseInt(ww1); Integer w1 = Integer.valueOf(ww1); Integer w2 = Integer.valueOf(ww2); Integer w3 = Integer.valueOf(ww3); db.zapis(60,w1,w2,w3); } public void onDestroy() { super.onDestroy(); cursor.close(); SilkaDataBaseHelper.close(); } //COFANIE NA PASKU AKCJI @Override public boolean onSupportNavigateUp(){ finish(); return true; } } lass SilkaDataBaseHelper extends SQLiteOpenHelper { private static final String DB_NAME = "silka"; private static final int DB_VERSION = 1; SilkaDataBaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE WYNIKI (" + "ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "KG INTEGER, " + "JED INTEGER, " + "DWA INTEGER, " + "TRZY INTEGER);" + ""); System.out.println("baza stworzona"); db.close(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { System.out.println("ss"); ; } //DODAWANIE DO BAZY public void zapis(int kg, int l1, int l2, int l3) { SQLiteDatabase db = getWritableDatabase(); ContentValues dane = new ContentValues(); dane.put("KG", kg); dane.put("JED", l1); dane.put("DWA", l2); dane.put("TRZY", l3); db.insertOrThrow("WYNIKI", null, dane); System.out.println("zapisane" + kg + " " + l1 + " " + l2 + " " + l3); } public Cursor daj3() { String[] kolumny = { "ID","KG", "JED", "DWA", "TRZY"}; SQLiteDatabase db = getReadableDatabase(); System.out.println("przed"); Cursor kursor = db.query("WYNIKI", kolumny, null, null, null, null, "ID DESC", "1"); System.out.println("po"); return kursor; } } 来在端点显示方法,这里是一个示例:

http.HandleFunc

注意: 避免在生产中使用默认的http客户端。您可以尝试使用一些HTTP框架,例如package main import ( "fmt" "io/ioutil" "log" "net/http" "os" ) // Todo Structure type Todo struct { userID int id int title string completed bool } func main() { http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, callHTTP()) }) if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal(err) } } func callHTTP() string { var ( response *http.Response err error responseData []byte ) if response, err = http.Get("http://jsonplaceholder.typicode.com/todos/1"); err != nil { fmt.Println(err.Error()) os.Exit(1) } if responseData, err = ioutil.ReadAll(response.Body); err != nil { log.Fatal(err) } ret := string(responseData) fmt.Println(ret) return ret } 。我更喜欢GIN,在这里您可以查看一些代码作为示例:https://github.com/alessiosavi/StreamingServer