B4J Question MongoDB JSON parsing - missing quotes

MM2forever

Active Member
Licensed User
Longtime User
Helllo all

Im facing an issue with parsing JSON from a MongoDB "document". This is the document as copied via Robo T3 mongoDB tool:
B4X:
{
    "_id" : ObjectId("5d36c72cd7f1cd20e4bdafa6"),
    "Typ" : "Belastung",
    "Konto" : "Privatkonto \"Haushalt\"",
    "Neuer Saldo" : "4'814.51 CHF (per 23.07.2019 06:14)",
    "Betrag" : "19.99 CHF",
    "Buchungsdatum" : "23.07.2019",
    "Valutadatum" : "23.07.2019",
    "Buchung" : "\nEinkauf/Tanken Coop TS\n22.07.2019/06:22 / V PAY-Karten-Nr. 60338465\nKeine\n\n"
}

as you can see it follows the correct JSON scheme of "key" : "value" in quotes and quotes within the value strings are properly escaped with \"

Now when I use .find() and get a List returned:

B4X:
(ArrayList) [{Typ=Belastung, Konto=Privatkonto "Haushalt"}, {Typ=Belastung, Konto=Privatkonto "Haushalt"}, {Typ=Gutschrift, Konto=Privatkonto "Haushalt"}]

Navigiting this in the JSON parser will cause an exception
java.lang.RuntimeException: org.json.JSONException: Unterminated object at character 33 of {Typ=Belastung,Konto=Privatkonto "Haushalt"}
(understandable)

What am I doing wrong? How can I avoid this?
I tried to manually fix things with Regex but it seems like a big mess (e.g. I dont know what happens if i add quotes to non-String values?) to do it that way and I am not good with regex anyways.

Thanks :)
 

MM2forever

Active Member
Licensed User
Longtime User
Sorry guys, I found a way in the meantime, altough I don't know if its good practice:
B4X:
Dim jg As JSONGenerator 'temporary JSON generator
jg.Initialize(mongodata.Get(i)) ' initializing it with the JSON from the MongoDB
      
JSON.Initialize(jg.ToString) ' tostring to parse it again
Dim root As Map = JSON.NextObject
Dim Typ As String = root.Get("Typ") ' Those will have correct quotes
Dim Konto As String = root.Get("Konto") 'yay!
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
Sorry guys, I found a way in the meantime, altough I don't know if its good practice:
B4X:
Dim jg As JSONGenerator 'temporary JSON generator
jg.Initialize(mongodata.Get(i)) ' initializing it with the JSON from the MongoDB
     
JSON.Initialize(jg.ToString) ' tostring to parse it again
Dim root As Map = JSON.NextObject
Dim Typ As String = root.Get("Typ") ' Those will have correct quotes
Dim Konto As String = root.Get("Konto") 'yay!
All good. Browse my examples how to parse Json structures (array, list, map, w/o php, etc.). Search for Json & list or similar.
 
Upvote 0
Top