I am using JsonTextWriter
to construct a JSON string where the end result needs to look like this. The data property value "John Doe" will get replaced by a string variable to search for different names in a REST API call:
{
"fields": [
"name",
"Company.name",
"email",
"mobile"
],
"query": {
"group": {
"operator": "AND",
"rules": [
{
"condition": "CONTAINS",
"moduleName": "Contact",
"field": {
"fieldName": "name"
},
"data": "John Doe"
}
]
}
}
}
This JsonTextWriter
method is very hard for me to read, not intuitive. I'm guessing there is a way to instead create a class with all the properties and assign values? But I can't figure out how to deal with the nested stuff. Maybe better to use raw JSON for some parts to make it easier to make the code structure somewhat represent the final JSON? Here is the code I have now, it works, it is just clunky to read/edit. I'm thinking of something like LINQ to XML, where when you look at the LINQ code it is easy to "see" the XML structure :
Dim sb As StringBuilder = New StringBuilder()
Dim jw As JsonWriter = New JsonTextWriter(New StringWriter(sb))
jw.Formatting = Formatting.Indented
jw.WriteStartObject()
jw.WritePropertyName("fields")
jw.WriteStartArray()
jw.WriteValue("name")
jw.WriteValue("Company.name")
jw.WriteValue("email")
jw.WriteValue("mobile")
jw.WriteEndArray()
jw.WritePropertyName("query")
jw.WriteStartObject()
jw.WritePropertyName("group")
jw.WriteStartObject()
jw.WritePropertyName("operator")
jw.WriteValue("AND")
jw.WritePropertyName("rules")
jw.WriteStartArray()
jw.WriteStartObject()
jw.WritePropertyName("condition")
jw.WriteValue("CONTAINS")
jw.WritePropertyName("moduleName")
jw.WriteValue("Contact")
jw.WritePropertyName("field")
jw.WriteStartObject()
jw.WritePropertyName("fieldName")
jw.WriteValue("name")
jw.WriteEndObject()
jw.WritePropertyName("data")
jw.WriteValue("John Doe")
jw.WriteEndObject()
jw.WriteEndArray()
jw.WriteEndObject()
jw.WriteEndObject()
jw.WriteEndObject()
debug.writeline(sb.ToString)