B4J Question An easy way to turn json into b4j object

xulihang

Active Member
Licensed User
Longtime User
I am trying elasticsearch. It uses a query language based on json.

There are many examples on its tutorial, like:

B4X:
GET /bank/_search
{
  "query": {
    "bool": {
      "should": [
        { "match": { "address": "mill" } },
        { "match": { "address": "lane" } }
      ]
    }
  }
}

And in the jelasticsearch example, these queries are made like this:

B4X:
        Dim Highlighter As Map = CreateMap( _
            "pre_tags": Array("<b>"), "post_tags": Array("</b>"), _
            "fields": CreateMap(field: CreateMap()))

        esres = Main.esclient.Search("documents", "txt", _
            CreateMap("query": Query, _
             "from":from, _
             "highlight": Highlighter, _
             "_source": "title"))

Is there an easy way to turn json into b4j object?
 

xulihang

Active Member
Licensed User
Longtime User
I have come up with two ways:

One is to directly modify json string and use JsonGenerator.

The other is to create a helper class to build json string:

B4X:
Sub Process_Globals
   
End Sub

Sub stringToMap(jsonString As String) As Map
    Log(jsonString)
    Dim json As JSONParser
    json.Initialize(jsonString)
    Return json.NextObject
End Sub

Sub matchDict(field As String, queryString As String) As Map
    Return CreateMap("match":CreateMap(field:queryString))
End Sub

Sub boolDict(boolType As String,conditions As List) As Map
    Return CreateMap("bool":CreateMap(boolType:conditions))
End Sub

To use:

B4X:
    Dim conditions As List
    conditions.Initialize
    conditions.Add(QueryDSLMaker.matchDict("text",text))
    conditions.Add(QueryDSLMaker.matchDict("sourceOrTarget",sourceOrTarget))
    Dim Query As Map
    Query = QueryDSLMaker.boolDict("must",conditions)

creates json like this:

B4X:
{
    "bool": {
        "must": [
            {
                "match": {
                    "sourceOrTarget": "target"
                }
            },
            {
                "match": {
                    "text": "the"
                }
            }
        ]
    }
}
 
Upvote 0
Top