[英]How to write a post method which accepts JSON in Nancy and how to call it form a C# client?
[英]How to print JSON to C# in nancy
我有一個.json
文件名為file.json
。 當 URL 為localhost:8080/data
時,我想在屏幕上打印 JSON 文件具有的名稱和年齡等localhost:8080/data
。 這是我嘗試過的,它在網頁 System.Collections.Generic.List`1[NancyWinForm.MainMod+Item] 上出現以下錯誤
Get["/data"] = x =>
{
return LoadJson();
};
}
public string LoadJson()
{
StreamReader r = new StreamReader("file.json");
string json = r.ReadToEnd();
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
String items2 = items.ToString();
return items2;
}
public class Item
{
public int age;
public string name;
}
沒有必要反序列化您的文件內容,然后使用ToString()
將其轉換回 json 這也不會將您的列表序列化為 json 字符串。
而是嘗試以下操作:
Get["/data", true] = async (param, cancellationToken) =>
{
string json;
try
{
using (var sr = new StreamReader("file.json"))
{
json = await sr.ReadToEndAsync();
// if you want to project your data into another form you
// can do this, as @Bishoy suggested
var itemList = JsonConvert.DeserializeObject<List<Item>>(json);
json = string.Join(Environment.NewLine,
itemList.Select(x => $"Age:{x.Age}, Name: {x.Name}"));
}
}
catch (Exception e)
{
return HttpStatusCode.InternalServerError;
}
return json;
};
我猜你在追求類似的東西:
public string LoadJson()
{
StreamReader r = new StreamReader("file.json");
string json = r.ReadToEnd();
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
return string.Join("\r\n", items.Select(i => i.ToString()).ToArray());
}
public class Item
{
public int age;
public string name;
public override string ToString() => $"Age: {age}, Name: {name}";
}
我所做的更改如下:
ToString
方法以在方法中呈現Item
類LoadJson
方法中,為列表中的每個項目返回了ToString
方法的所有結果的連接字符串如果您想要的是顯示 JSON 格式,您可以使用 JSON 序列化或實際上只是按原樣顯示文件的內容:)
此外,我建議遵循 C# 約定並使用 PascalCasing 命名Item
公共屬性,並使用相應標簽的名稱對其進行標記。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.