Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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)?

share|improve this question
    
Just BTW, if you go for the PHP style there's one aspect of json_decode() I think is problematic: It's sloppy about what it returns. You don't know if it's returning null because that was the normally-decoded JSON value, or whether there was an error. You then need to call another function just to figure out what kind of error may-or-may-not have occurred. I'd rather have a richer result object or throw an exception or something. –  Darien Sep 22 '13 at 21:37

2 Answers 2

Since C is statically typed and JSON is not, and any JSON element can be a null, a number, a string, a boolean, an object, or an array, you basically have to do it as "a rip off the OOP way". Create a record type that represents a JSON value, and has a member that's a tag indicating which type of JSON value it is, and then create "subclasses" that build on this record type. To represent JSON well in C, you basically have to recreate OOP and polymorphism.

Anything that uses a JSON value will have to take a pointer to the base record type. Remember that objects are always reference types, poor C++ language design choices notwithstanding, because otherwise it screws up polymorphism, and you require polymorphism to do this right. When you find out what kind of "subclass" you're actually working with, (by checking the tag member,) you can cast your JSON Value pointer to the appropriate subclass type pointer to access the rest of the record.

share|improve this answer
3  
ummm, in C I can just use a union? No need for the subclasses really... The identifier and a single structure is probably simple and sufficient. Or why shouldn't one just store a single pointer to the data alongside the type? (we're talking about C here and not some OOP language). You can also take a function pointer to mimic polymorph behaviour. –  Falcon Sep 22 '13 at 21:46
    
@Falcon: You can try that if you really want, but IME union types tend to be more trouble than they're worth most of the time. –  Mason Wheeler Sep 22 '13 at 23:44

You're doing it right. This is an old problem - JSON's varying types and unordered presentation aspects are essentially the same as those presented by every data-markup language going back to at least SGML.

For C in particular, there are lots of options already available. Googling "C JSON Parser" turns up many, including jsmn, which looks like it learned many of the lessons that Java processing of XML had to teach. More directly to the point, this has been addressed on StackOverflow again and again. And, of course Crockford's JSON.org lists 16 different C implementations of JSON.

share|improve this answer
    
I wasn't exactly asking about JSON parsers(as you mentioned, there are a bunch of them at json.org). however, my question was more about organizing the code that uses the parser. –  Rev3rse Sep 21 '13 at 20:15
    
If you know what objects you're going to be consuming it should be fairly straightforward to map the data classes onto structures, define the structures in C, then map the incoming data to those. Straightforward, but ugly. FWIW this recently pushed me into C++ for one project because C and JSON gets ugly fast if you're not building your JSON with the C consumer in mind (collections don't always map nicely to integer-indexed arrays). That project bridges C-only embedded hardware to websites that use JSON. –  Ӎσᶎ Oct 22 '13 at 21:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.