我正在使用最新版本的发送网格,我的小胡子模板在本地运行良好。我在发送网格上创建了一个动态模板,现在我需要在模板中发送一个复杂对象作为输入数据。
例如
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{#trueFlag}}
true flag :<p>{{orderId}}</p>
{{/trueFlag}}
-----
{{^falseFlag}}
false flag : <p>{{orderId}}</p>
{{/falseFlag}}
href
<a href="{{websiteUrl}}?">WeSome</a>
image
<img src="{{imageUrl}}" alt="{{imageAlt}}">
{{#features}}
{{.}}
{{/features}}
-----
feature
<p>{{feature.featureName}}</p>
<p>{{feature.featureType}}</p>
-----
{{#features}}
{{featureName}}
{{featureType}}
{{/features}}
-----------
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Price</th>
</tr>
{{#features}}
<tr>
<td>{{featureName}}</td>
<td>{{featureType}}</td>
</tr>
{{/features}}
</table>
</body>
</html>
复杂对象是
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
@Data
public class TemplateObject {
private boolean trueFlag;
private boolean falseFlag;
private String orderId;
private String websiteUrl;
private String imageUrl;
private String imageAlt;
List<Feature> features;
Feature feature;
@Data
@AllArgsConstructor
public static class Feature {
String featureName;
String featureType;
}
}
从上述对象生成的 JSON 是
{
"trueFlag": true,
"falseFlag": false,
"orderId": "1",
"websiteUrl": "wesome.org",
"imageUrl": "http://s7d7.scene7.com/is/image/BedBathandBeyond/1565212198531p?$130$",
"imageAlt": "2Cuisinart® Replacement1 Charcoal Water Filters (Set of 2)",
"features": [
{
"featureName": "feature 2",
"featureType": "feature type 2"
},
{
"featureName": "feature 3",
"featureType": "feature type 3"
}
],
"feature": {
"featureName": "feature 1",
"featureType": "feature type 1"
}
}
这个 JSON 是正确的,我已经使用 web 应用程序上的发送网格测试 JSON 数据功能对其进行了验证。
现在我需要将这个复杂的对象传递给 SendGrid。
Mail mail = new Mail();
Email fromEmail = new Email();
fromEmail.setName("shri");
fromEmail.setEmail("shrikant.sharma606@gmail.com");
mail.setFrom(fromEmail);
mail.setTemplateId("d-xxxx");
Personalization personalization = new Personalization();
Gson gson = new Gson();
String s = gson.toJson(templateObject);
// if i paas data as individual key value its working
personalization.addDynamicTemplateData("imageUrl", "http://s7d7.scene7.com/is/image/BedBathandBeyond/1565212198531p?$130$");
// but i need to paas this object
personalization.addDynamicTemplateData("dynamic_template_data", s);
personalization.addTo(new Email("abcd@gmail.com"));
System.out.println(gson.toJson(personalization));
mail.addPersonalization(personalization);