3 回答

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

TA貢獻1829條經驗 獲得超4個贊
你是對的。所以問題似乎出在別處,因為如果我的 python 中只有 print(sys.argv?1?),我將收到如下數據:“[{SearchTerm_id:1,Term:Lorem ipsun},{SearchTerm_id:2,洛雷姆·伊普蘇姆}]”
C# 實際上是在不使用轉義字符的情況下格式化 JSON,這與原始問題所說的相反。所以它正在做它應該做的事情。如果打印文本,您會看到{"SearchTerm_id":1,"Term":"lorem ipsum"}
。
但是,Python 接收的 JSON不帶雙引號。從 Python 打印顯示{SearchTerm_id:1,Term:lorem ipsum}
.?當您json.loads
使用錯誤的 JSON 進行調用時,它會拋出異常。
json.decoder.JSONDecodeError:?Expecting?property?name?enclosed?in?double?quotes:?line?1?column?2?(char?1)
看起來,當您Process.Start()
在 C# 中調用時,shell 會從ProcessStartInfo.Arguments
列表中的 JSON 中刪除雙引號。所以Python接收的參數不帶雙引號。
解決方案
在 C# 中,序列化后更新 JSON 字符串,以便轉義雙引號。這里有一些代碼可以幫助解決這個問題。
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);
- 3 回答
- 0 關注
- 288 瀏覽
添加回答
舉報