3 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
var json = JsonConvert.SerializeObject(searchTerms);
如果您正在調(diào)試器中查看結(jié)果。調(diào)試器僅顯示\
作為視覺(jué)輔助,表示字符串,就像必須用 C# 編寫一樣。
嘗試運(yùn)行Console.Write(json);
并查看輸出。
輸出將不包含轉(zhuǎn)義字符。這才是真正的價(jià)值。

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
你是對(duì)的。所以問(wèn)題似乎出在別處,因?yàn)槿绻业?python 中只有 print(sys.argv?1?),我將收到如下數(shù)據(jù):“[{SearchTerm_id:1,Term:Lorem ipsun},{SearchTerm_id:2,洛雷姆·伊普蘇姆}]”
C# 實(shí)際上是在不使用轉(zhuǎn)義字符的情況下格式化 JSON,這與原始問(wèn)題所說(shuō)的相反。所以它正在做它應(yīng)該做的事情。如果打印文本,您會(huì)看到{"SearchTerm_id":1,"Term":"lorem ipsum"}
。
但是,Python 接收的 JSON不帶雙引號(hào)。從 Python 打印顯示{SearchTerm_id:1,Term:lorem ipsum}
.?當(dāng)您json.loads
使用錯(cuò)誤的 JSON 進(jìn)行調(diào)用時(shí),它會(huì)拋出異常。
json.decoder.JSONDecodeError:?Expecting?property?name?enclosed?in?double?quotes:?line?1?column?2?(char?1)
看起來(lái),當(dāng)您Process.Start()
在 C# 中調(diào)用時(shí),shell 會(huì)從ProcessStartInfo.Arguments
列表中的 JSON 中刪除雙引號(hào)。所以Python接收的參數(shù)不帶雙引號(hào)。
解決方案
在 C# 中,序列化后更新 JSON 字符串,以便轉(zhuǎn)義雙引號(hào)。這里有一些代碼可以幫助解決這個(gè)問(wèn)題。
using Newtonsoft.Json;
using System.Text;
public static class JsonHelper
{
? ? public static string ToJsonString(
? ? ? ? object obj,
? ? ? ? bool escapeDoubleQuotes = false)
? ? {
? ? ? ? string serialized = JsonConvert.SerializeObject(obj);
? ? ? ? if (escapeDoubleQuotes)
? ? ? ? {
? ? ? ? ? ? // e.g., '{"key":"value"}' -> '{\"key1\":\"value\"}'
? ? ? ? ? ? // Do this when need to pass json as cmd line arg via System.Diagnostics.Process. Else shell will strip the double quotes, so your new process might not know what to do with it
? ? ? ? ? ? serialized = serialized.Replace(@"""", @"\""");
? ? ? ? }
? ? ? ? return serialized;
? ? }
}
所以為了讓他的原始代碼工作,OP只需改變
var json = JsonConvert.SerializeObject(searchTerms);
到
var json = JsonHelper.ToJsonString(searchTerms, escapeDoubleQuotes: true);

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以使用 messagePack 庫(kù)。我設(shè)法以高性能在 python 和 c# 之間傳遞字符串和其他類型。
- 3 回答
- 0 關(guān)注
- 267 瀏覽
添加回答
舉報(bào)