The SDK provides several ways to work with structured JSON data from Gemini:
Automatic Deserialization
GenerateObjectAsync<T>(request): Directly returns a deserialized object of type T.GenerateContentAsync<T>(request): Returns a response that can be converted using .ToObject<T>().UseJsonMode<T>(): An extension method for GenerateContentRequest that instructs the model to return a JSON response matching type T.
Manual JSON Parsing
If you need more control, you can manually configure the GenerationConfig with ResponseMimeType = "application/json" and a ResponseSchema. To extract data from a standard response, use response.ExtractJsonBlocks() to retrieve raw JSON blocks, then call .ToObject<T>() on each block.
// Option 1: Direct deserialization
var myObject = await model.GenerateObjectAsync<SampleJsonClass>(request);
// Option 2: Using JSON mode in request
var request = new GenerateContentRequest();
request.UseJsonMode<SampleJsonClass>();
request.AddText("Give me a response.");
var response = await model.GenerateContentAsync(request);
var myObject = response.ToObject<SampleJsonClass>();
// Option 3: Manual extraction from blocks
var response = await model.GenerateContentAsync(request);
var jsonBlocks = response.ExtractJsonBlocks();
var myObjects = jsonBlocks.Select(block => block.ToObject<SampleJsonClass>());