如何将json添加到RestSharp POST请求中

时间:2016-08-25 19:23:54

标签: c# json restsharp

我有以下JSON字符串作为字符串参数传递给我的c#代码 - AddLocation(string locationJSON):

public string AddLocation(string locationJSON)
{
    var client = new RestClient(_authorizationDataProvider.LocationURL);
    var request = new RestRequest(Method.POST);
    request.RequestFormat = DataFormat.Json;
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("Authorization", _authorizationResponse.Token);
    ...
    request.AddJsonBody(locationJSON);
    var response = client.Execute(request);
}

我试图将JSON添加到这样的RestSharp POST请求中,但它无效:

{"code":"invalid_json","details":{"obj.address":[{"msg":["error.path.missing"],"args":[]}],"obj.rankingKeywords":[{"msg":["error.path.missing"],"args":[]}],"obj.alternatePhoneNumbers":[{"msg":["error.path.missing"],"args":[]}],"obj.busName":[{"msg":["error.path.missing"],"args":[]}],"obj.accountId":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateEmails":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateWebsites":[{"msg":["error.path.missing"],"args":[]}],"obj.email":[{"msg":["error.path.missing"],"args":[]}],"obj.primaryKeyword":[{"msg":["error.path.missing"],"args":[]}],"obj.auditOnly":[{"msg":["error.path.missing"],"args":[]}]}}

响应回复为"错误请求"。如果我在调试器中检查响应,这是我得到的:

{\"accountId\":\"57abb4d6aad4def3d213c25d\",\"address\":{\"city\":\"TEST\",\"country\":\"TEST\",\"postalCode\":\"TEST\",\"state\":\"TEST\",\"street\":\"TEST\"},\"alternateEmails\":[{\"email\":\"TEST\"}],\"alternatePhoneNumbers\":[{\"phoneNumber\":\"TEST\"}],\"alternateWebsites\":[{\"website\":\"TEST\"}],\"auditOnly\":false,\"busName\":\"84e7ef98-7a9f-4805-ab45-e852a4b078d8\",\"email\":\"TEST EMAIL\",\"primaryKeyword\":\"TEST\",\"primaryPhone\":\"TEST\",\"rankingKeywords\":[{\"keyword\":\"TEST\",\"localArea\":\"TEST\"}],\"resellerLocationId\":\"06b528a9-22a6-4853-8148-805c9cb46941\",\"website\":\"TEST\"}

我在调用AddJsonBody之后检查了请求参数,并且值似乎包括双引号的转义序列 - 这似乎是问题。

import sys
import matplotlib
matplotlib.use("Qt5Agg")
import numpy as np
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5.QtWidgets import QWidget, QMainWindow, QApplication, QSizePolicy, QVBoxLayout, QPushButton
from PyQt5.QtCore import *
from PyQt5.QtGui import QCursor

class MyMplCanvas(FigureCanvas):
    #Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.fig = fig
        self.axes = fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        self.axes.hold(False)

        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass


class MyStaticMplCanvas(MyMplCanvas):
    #Simple canvas with a sine plot.
    def compute_initial_figure(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2*pi*t)
        self.axes.plot(t, s)

class PlotDialog(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.plot_layout = QVBoxLayout(self)
        self.plot_canvas = MyStaticMplCanvas(self, width=5, height=4, dpi=100)

        self.navi_toolbar = NavigationToolbar(self.plot_canvas, self)
        self.plot_layout.addWidget(self.plot_canvas)  # the matplotlib canvas
        self.plot_layout.addWidget(self.navi_toolbar)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    dialog = PlotDialog()
    dialog.show()
    sys.exit(app.exec_())

所以我的问题是如何将json字符串添加到请求正文中?

3 个答案:

答案 0 :(得分:14)

我也遇到过这个问题。尝试这样的事情,而不是public bool GetKeyPressed(KeyCode key) { for (int i = 0; i < keys.Count; i++) if (keys[i].key == key && keys[i].pressed) return true; return false; }

AddJsonBody

答案 1 :(得分:6)

这应该有效:

request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(yourObject), ParameterType.RequestBody);

如果直接添加序列化对象,问题是Json转换在每个“。”之前添加“\”。

答案 2 :(得分:1)

我已经尝试过了,而且效果很好,

 request.AddHeader("cache-control", "no-cache");
 request.AddHeader("authorization", "Bearer " + 'your token key');
 request.AddHeader("accept", "application/json");