How to parse JSON string
JSON is a popular data representation format. This article shows how to parse a JSON string using Windows Phone and Symbian C++, and provides links to libraries that can be used to parse JSON in Qt.
Contents |
JSON Parsing in Windows Phone
The code snippet below shows how the json2csharp and json.net are used to parse JSON. The code given below parses the response received by Google's translator which is in JSON format.
private void ParseJson()
{
var jsonString =
"{\"responseData\": {\"translatedText\":\"אני ילד\"}, \"responseDetails\": null, \"responseStatus\": 200}";
RootObject jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
MessageBox.Show(jsonObject.responseData.translatedText);
}
//This class was generated with json2csharp
public class ResponseData
{
public string translatedText { get; set; }
}
//This class was generated with json2csharp
public class RootObject
{
public ResponseData responseData { get; set; }
public object responseDetails { get; set; }
public int responseStatus { get; set; }
}
Symbian C++ parsing library
The Symbian C++ parser is called s60-json-library. It is hosted on code.google.com here and can be downloaded from: Media:S60-json-library.zip.
The code snippet below shows how the API is used to parse JSON. The code given below parses the response received by Google's translator which is in JSON format.
_LIT(KTestFormatedJson, "{\"responseData\": {\"translatedText\":\"אני ילד\"}, \"responseDetails\": null, \"responseStatus\": 200}");
CJsonBuilder* jsonBuilder = CJsonBuilder::NewL();
// this will create json string representation in memory
jsonBuilder->BuildFromJsonStringL(iKTestFormatedJson);
CJsonObject* rootObject;
CJsonObject* textObj;
jsonBuilder->GetDocumentObject(rootObject);
if(rootObject)
{
TBuf<256> message;
rootObject->GetObjectL(_L("responseData"),textObj);
textObj->GetStringL(_L("translatedText"),message);
}
// we need manually release created object
delete rootObject;
// releases only jsonBuilder object, not objects which was created by him
delete jsonBuilder;
JSON Parsing in Qt
- QJson - a library for parsing JSON in Qt
JSON in Java
See J2ME clients for JSON services made easy: the complete implementation
(no comments yet)