如果有人帮助我在C#中构建JArray只使用值而没有键,我将非常感激。这是我想要的一个例子:
{[
"ZGVyZWtAcG9zc2tpLmNvbQ==",
"YW5kcmVAbGltYWcubmV0",
"YW5keUBiYW9iYW9tYWlsLmNvbQ==",
"dGVzdEBraW5ub3YuY29t",
"c2hhaG5hd2F6LmFsYW0xM0Bob3RtYWlsLmNvbQ==",
"YnJlYW5uQGVtYWlsLmNvbQ=="
]}
这是我为它编写的代码,但是我得到了一个例外,因为当我声明JObject时,它需要我有一个键和一个值,但我只需要该值,因为我将此数组作为参数发送给一个API,他们需要特定的格式。
以下是导致问题的代码:
var recipients = new JArray();
foreach (var c in retrievedContacts.recipients)
{
var jsonObject = new JObject();
jsonObject.Add(c.id);
recipients.Add(jsonObject);
}
dynamic addToListResponse = await sg.client.contactdb.lists._(listJson.lists[0].id).recipients.post(requestBody: recipients);
最后一行向SendGrid发送一个帖子请求。这里列表id有效,除了在循环中添加json对象外,一切正常。请帮忙!
答案 0 :(得分:1)
要创建具有指定值的JArray
,您可以使用JToken.FromObject()
将c.id
转换为JToken
,然后将construct转换为JArray
var recipients = new JArray(retrievedContacts.recipients.Select(c => JToken.FromObject(c.id)));
如下:
id
特别是,如果c.id
是字节数组,则此方法有效。在这种情况下,Json.Net会将其转换为base64字符串。样本fiddle。
如果FromObject()
已一个字符串(在您的问题中,您没有指定其类型),您可以跳过对var recipients = new JArray(retrievedContacts.recipients.Select(c => c.id));
的调用并将其添加为 - 没有序列化:
public class Menu{
public void purchaseItems(){ // pass an argument or return something depending on what you need
// figure out how you purchase items
}
public void displayCurrentPurchases(){
// figure out how you display the cart (your cart can be a List, Map, or even a class)
}
public void printReceipt(){
// figure out how you print the receipt
//somewhere here you would need to call your computeTaxes method
double netAmount = computeTaxes(grossAmount);
}
/* It's a good idea to limit a method to doing only one thing as much as possible, so you might need to make private methods such as computing for taxes below */
private double computeTaxes(double totalAmount){
return total * 0.098;
}
// and so on...
}