Azure Function CosmosDB触发器返回编码数据问题咨询
Hey Evan, I’ve run into this exact issue before—when you directly log or concatenate a Document object, it doesn’t output the readable JSON you expect because the default ToString() method for the Document class returns an internal encoded representation, not the plain JSON content of your document. Let’s fix this with a couple straightforward solutions:
Solution 1: Use Document.ToString() with Formatting
The Document class has an overload of ToString() that lets you get properly formatted JSON directly. Just specify a formatting option (like Formatting.None for compact JSON or Formatting.Indented for pretty-printed output):
public static void Run(IReadOnlyList<Document> documents, TraceWriter log) { if (documents != null && documents.Count > 0) { log.Info($"Number of modified documents: {documents.Count}"); foreach (var doc in documents) { // Get readable JSON from the Document object string docJson = doc.ToString(Newtonsoft.Json.Formatting.None); log.Info($"Modified document content: {docJson}"); } } }
Solution 2: Deserialize to a Strongly Typed Class
If you plan to work with the document data (not just log it), converting the Document to a custom class makes your code cleaner and easier to maintain. First, define a class that matches your document structure:
public class TaskDocument { public string _id { get; set; } public string id { get; set; } public string type { get; set; } public string information { get; set; } }
Then use the ToObject<T>() method on the Document to convert it, and optionally serialize it back to JSON if needed:
public static void Run(IReadOnlyList<Document> documents, TraceWriter log) { if (documents != null && documents.Count > 0) { foreach (var doc in documents) { // Convert Document to your custom class TaskDocument task = doc.ToObject<TaskDocument>(); // Log specific fields for clarity log.Info($"Updated task: ID={task.id}, Info={task.information}"); // Or serialize the class back to readable JSON string taskJson = Newtonsoft.Json.JsonConvert.SerializeObject(task); log.Info($"Full task JSON: {taskJson}"); } } }
Bonus: Check Your Cosmos DB Binding Version
Occasionally, older versions of the Azure Functions Cosmos DB binding can have quirks with serialization. Make sure you’re using the latest stable version of the Microsoft.Azure.WebJobs.Extensions.CosmosDB NuGet package in your project—this can prevent unexpected encoding issues.
The core issue here is that the default ToString() for Document isn’t designed for human-readable output; it’s an internal representation. By using either the formatted ToString() overload or converting to a strongly typed object, you’ll get the clear, unencoded data you expect.
内容的提问来源于stack exchange,提问作者Evan Park

