Parsing a JSON Response from a .Net webservice
- by Maskau
Just to get this out in the open I am new to JAVA, KSOAP, and JSON. So I'll try to explain this the best I can.
A while ago I created a webservice to be consumed by Blackberry Apps that we're built using the plug in for Visual Studio. Now the project I am working on, I want to consume the same webservice for Android devices. For the most part I have the base code for the Android app done and working. Here's my problem:
I can successfully call the webservice and get a response. I know from creating the webservice that it sends a JSON response. My problem is trying to parse through the JSON response. I have found a few examples that I have been suiting to my needs however I am hung up on one thing.
In the JSON each element is preceeded by "anyType" which is forcing my code to return no results (Ultimately I am binding the data to an ArrayList) Here's what I get if I "getProperty(0).toString()...
anyType{Artist=anyType{TrackName=Champagne Supernova;};
Here is the code I am using to parse the JSON Object....
SoapObject gr = (SoapObject)envelope.getResponse();
String ro = gr.getProperty(0).toString();
//Added just to see structure of response
Artist_Result.add(gr.toString());
if (ro.startsWith("{"))
{
JSONObject JSONObj = new JSONObject(ro);
Iterator<String> itr = JSONObj.keys();
while (itr.hasNext())
{
String key = (String)itr.next();
String value = JSONObj.getString(key);
//bundleResult.putString(key, value);
Artist_Result.add(value);
}
}
else if (ro.startsWith("["))
{
JSONArr = new JSONArray(ro);
for (int i = 0; i < JSONArr.length(); i++)
{
JSONObj = (JSONObject)JSONArr.get(i);
//bundleResult.putString(String.valueOf(i), JSONObj.toString());
Artist_Result.add(JSONObj.toString());
}
}
WebService Code:
[WebMethod]
[return: System.Xml.Serialization.XmlArrayItemAttribute(typeof(Artist))]
public Artist[] GetArtist(string ArtistQuery)
{
// All the SQL Stuff Here
SqlDataReader sReader;
sReader = cmd.ExecuteReader();
List<Artist> Artists = new List<Artist>();
while (sReader.Read())
{
Artist result = new Artist();
result.TrackName = sReader.GetString(0);
Artists.Add(result);
}
sReader.Close();
sqlConn.Close();
return Artists.ToArray();
}
public class Artist
{
public string TrackName;
}
Sample of XML Output from a browser:
<?xml version="1.0" encoding="utf-8" ?>
- <ArrayOfArtist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://bb.mcrcog.com/">
- <Artist>
<TrackName>Champagne Supernova</TrackName>
</Artist>
- <Artist>
<TrackName>Don't Look Back In Anger</TrackName>
</Artist>
- <Artist>
<TrackName>D'you Know What I Mean</TrackName>
</Artist>
- <Artist>
<TrackName>Go Let It Out</TrackName>
</Artist>
I have a feeling I will need to implement a Class, and Getters/Setters on the Android side. I'm just not sure how to go about doing that. Any help would be greatly appreciated!