An ideal way to decode JSON documents in C?
Posted
by
AzizAG
on Programmers
See other posts from Programmers
or by AzizAG
Published on 2013-09-20T21:59:00Z
Indexed on
2013/10/22
22:02 UTC
Read the original article
Hit count: 277
Assuming I have an API to consume that uses JSON as a data transmission method, what is an ideal way to decode the JSON returned by each API resource? For example, in Java I'd create a class for each API resource then initiate an object of that class and consume data from it.
for example:
class UserJson extends JsonParser
{
public function UserJson(String document) {
/*Initial document parsing goes here...*/
}
//A bunch of getter methods . . . .
}
The probably do something like this:
UserJson userJson = new UserJson(jsonString);//Initial parsing goes in the constructor
String username = userJson.getName();//Parse JSON name property then return it as a String.
Or when using a programming language with associative arrays(i.e., hash table) the decoding process doesn't require creating a class:
(PHP)
$userJson = json_decode($jsonString);//Decode JSON as key=>value
$username = $userJson['name'];
But, when I'm programming in procedural programming languages (C), I can't go with either method, since C is neither OOP nor supports associative arrays(by default, at least).
What is the "correct" method of parsing pre-defined JSON strings(i.e., JSON documents specified by the API provider via examples or documentation)?
The method I'm currently using is creating a file for each API resource to parse, the problem with this method is that it's basically a lousy version of the OOP method, as it looks exactly like the OOP method but doesn't provide any OOP benefits(e.g., can't pass an object of the parser, etc.).
I've been thinking about encapsulating each API resource parser file in a publicly accessed structure(pointing all functions/publicly usable variables to the structure) then accessing the parser file code from within the structure(parser.parse()
, parser.getName()
, etc.). As this way looks a bit better than the my current method, it still just a rip off the OOP way, isn't it?
Any suggestions for methods to parse JSON documents on procedural programming lanauges? Any comments on the methods I'm currently using(either 3 of them)?
© Programmers or respective owner