I'm tried to parse some json array (with string and two-dimensional array) into objects array, but the solutions I found do not work (or I was looking bad).
Please, help me with the code to get an array of objects.
I found working method for Java (I tried it in Eclipse) this,
but I want it for Android (in Android Studio)
My json file:
[
{
"someString": "First string",
"someTwoDimArray":
[
["First_firstElement", "First_secondElement"],
[true, false]
]
},
{
"someString": "Second string",
"someTwoDimArray":
[
["Second_firstElement", "Second_secondElement"],
[true, true]
]
}
]
I have java class:
public class someClass {
String someString;
Object[][] someTwoDimArray;
}
What I need: (To process the data in the code later)
someClass[] someClasses = /* ??? */
Try something like this:
JSONArray jsonarray = new JSONArray(jsonStr);
int L = yourArrayWithJSON.length();
first = new String[L];
second = new String[L];
third = new String[L];
for (int i = 0; i < L; i++) {
JSONObject point = vpn.getJSONObject(i);
first[i] = point.getString("first");
second[i] = point.getString("second");
third[i] = point.getString("third");
String url = jsonobject.getString("url");
}
Ask, if you have any questions
Related
I am parsing some json in an app and I have come across arrays that sometimes have information in it:
{
"output": [
{
"id": "1521",
"name": "Apples",
}
]
}
and sometimes has nothing. e.g
{
"output": [
[]
]
}
I was parsing it by
JSONArray output = c.getJSONArray("output");
int outputLength = output.length();
for (int q = 0; q < outputLength; q++)
{
JSONObject d = outputs.getJSONObject(q);
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
but when it gets to the empty array it crashes.
I get the following error then:
01-19 01:08:00.237: W/System.err(17627): org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject
it crashes because it's trying to convert the jsonarray into an object and you can't do that so I tried getting the first array in output with:
JSONArray add = output.getJSONArray(0);
but that will crash as well because in the first output it's an object in it and not an array.
I don't have access or control over the json feed and I'm stuck at the moment as to how to parse the result.
The real answer is: "Fix whatever is generating that horrible JSON".
If that's not an option you're going to have to figure out exactly what you have before trying to access it. The JSONArray.optJSONObject() method can help with this; it returns null if the specified index doesn't contain a JSONObject:
JSONArray output = c.getJSONArray("output");
for (int q = 0; q < outputLength; q++)
{
JSONObject d = output.optJSONObject(q);
if (d != null)
{
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
}
Because you're parsing everything in the enclosing JSONArray as aJSONObject, all the entries would have to be formatted that way. For that to work, your source string would have to look like this:
[
{
"output": [
{
"id": "1521",
"name": "Apples"
}
]
},
{
"output": [
[]
]
}
]
Everything in the top-levelJSONArray is now a JSONObject and can be parsed accordingly. What's inside of those objects is your business (empty arrays are OK). A good resource for checking if a given JSON string is valid is this website.
Want Android Code For Following JSON Format...Bit Confused How to fetch value of array For Following Pattern..
{
"params": [
{
"answer_data_all": [
{
"id": "5",
"question_id": "14"
}
],
"form_data_all": [
{
"id": "1",
"name": "form 1"
}
]
}
]
}
You just have some nested JSONArray and JSONObject. Assuming you have this response in string format all you have to do is create JSONObject from that string and then extract what you need. As someone mentioned [ ] encloses JSONArray while { } encloses JSONObject
JSONObject mainObject = new JSONObject(stringResponse);
JSONArray params = mainObject.getJSONArray("params"); //title of what you want
JSONObject paramsObject = params.getJSONObject(0);
JSONArray answerData = paramsObject.getJSONArray("answer_data_all");
JSONArray formData = paramsObject.getJSONArray("form_data_all");
String id = formData.getJSONObject(0).getString("id");
You should be able to extract all the values doing something like this. Although I will say I think the formatting is odd. You're using single member arrays that just contain other objects. It would make much more sense to either use one array to hold all the object or just separate JSONObject. It makes it much easier to read and easier to parse.
Parsing a JSON is fairly simple. You could use GSON library by Google for example. Below is an example I wrote for your object/model:
class MyObject{
ArrayList<Params> params;
class Params {
ArrayList<AnswerData> answer_data_all;
ArrayList<FormData> form_data_all;
class AnswerData {
String id;
String question_id;
}
class FormData {
String id;
String name;
}
}
}
And then get an instance of your object with:
MyObject myObject = (MyObject) (new Gson()).toJson("..json..", MyObject.class);
JSONArray feed = feedObject.getJSONArray("params");
for(int i = 0; i<feed.length(); i++){
JSONArray tf = feed.getJSONArray(i);
for (int j = 0; j < tf.length(); j++) {
JSONObject hy = tf.getJSONObject(j);
String idt = hy.getString("id");
String name = hy.getString("name");
}
}
**NOTE: the 'feedObject' variable is the JSONObject you are working with..Although this your type of JSON feed is kinda mixed in terms of string names and all but this should do for now..
I'm developing an Android application that connects with Facebook using Springframework Android rest client.
With this URL:
https://graph.facebook.com/me/friends?access_token=AUTH_TOKEN
Facebook API returns:
{
"data": [
{
"name": "Friend1",
"id": "123456"
}
]
}
I want to parse the data[] values, as an array:
[
{
"name": "Friend1",
"id": "123456"
}
]
And get a FacebookFriend[].
How can I do it with GSON?
First, you'd need a FacebookFriend class (using public fields and no getters for simplicity):
public class FacebookFriend {
public String name;
public String id;
}
If you created a wrapper class such as:
public class JsonResponse {
public List<FacebookFriend> data;
}
Life becomes far simpler as you can simply do:
JsonResponse resp = new Gson().fromJson(myJsonString, JsonResponse.class);
And be done with it.
If you don't want to create an enclosing class with a data field, you'd use Gson to parse the JSON, then extract the array:
JsonParser p = new JsonParser();
JsonElement e = p.parse(myJsonString);
JsonObject obj = e.getAsJsonObject();
JsonArray ja = obj.get("data").getAsJsonArray();
(You can obviously chain all those methods, but I left them explicit for this demonstration)
Now you can use Gson to map directly to your class.
FacebookFriend[] friendArray = new Gson().fromJson(ja, FacebookFriend[].class);
That said, honestly it's better to use a Collection instead:
Type type = new TypeToken<Collection<FacebookFriend>>(){}.getType();
Collection<FacebookFriend> friendCollection = new Gson().fromJson(ja, type);
It seems, your array contain object.
you can parse it in following way.
JsonArray array = jsonObj.get("data").getAsJsonArray();
String[] friendList = new String[array.size()];
// or if you want JsonArray then
JsonArray friendArray = new JsonArray();
for(int i=0 ; i<array.size(); i++){
JsonObject obj = array.get(i).getAsJsonObject();
String name = obj.get("name").getAsString();
friendList[i] = name;
// or if you want JSONArray use it.
friendArray.add(new JsonPrimitive(name));
}
hi does anyone know how to create a Array that contains objects that in each objects contain several objects? i just can't seem to get my head round it
the structure should look like this
Array{[object]{subobject,subobject}
[object]{subobject,subobject}
}
heres what i have so far
JSONObject obj = new JSONObject(json2);
JSONObject objData = obj.getJSONObject("data");
fixturesArray = objData.getJSONArray("fixtures");
JSONArray FixArray = new JSONArray();
for(int t = 0; t < fixturesArray.length(); t++){
JSONObject fixObj = fixturesArray.getJSONObject(t);
String Matchdate = fixObj.getString("matchdate");
JSONObject DateObj = DateObj.put(Matchdate, DateObj);
heres my JSON essentially what i have if is a feed of fixtures i need to order them in to arrays of dates
{
"code":200,
"error":null,
"data":{
"fixtures":[
{
"kickoff":"15:00:00",
"matchdate":"2012-07-28",
"homescore":null,
"awayscore":null,
"attendance":null,
"homepens":null,
"awaypens":null,
"division_id":"5059",
"division":"Testing 1",
"comp":"LGE",
"location":null,
"fixture_note":null,
"hometeam_id":"64930",
"hometeam":"Team 1",
"awayteam_id":"64931",
"awayteam":"Team 2"
}, {
"kickoff":"15:00:00",
"matchdate":"2012-07-28",
"homescore":null,
"awayscore":null,
"attendance":null,
"homepens":null,
"awaypens":null,
"division_id":"5059",
"division":"Testing 1",
"comp":"LGE",
"location":null,
"fixture_note":null,
"hometeam_id":"64930",
"hometeam":"Team 1",
"awayteam_id":"64931",
"awayteam":"Team 2"
}
]
}
}
Do you mean that?:
JSONObject obj = new JSONObject();
obj.put("x", "1");
JSONObject parent_object = new JSONObject();
parent_object.put("child", obj);
JSONArray array = new JSONArray(parent_object.toString());
JSON String
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea"}
]
}
Here below I am fetching country details
JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
What I would suggest to do is to use JackSON JSON Parser library http://jackson.codehaus.org/ Then you can create a Class with the same fields as the JSON son the mapping from JSON To class will be direct.
So once you have all the items from JSON into a List of class you can order by dates or manipulate data as you want. Imagine that src is a String containing the JSON text. With JackSON lib you just need to do this.
ObjectMapper mapper = new ObjectMapper();
List<Fixture> result = mapper.readValue(src, new TypeReference<List<Fixture>>() { });
Here are two pieces of JSON which fit your description which is "Array that contains objects that in each objects contain several objects". The first method uses Arrays inside Objects. The other one uses Objects in Objects.
Method 1
[ { "name" : "first object in array" , "inner array" : [ { <object> } , { <object> } ] }
, { "name" : "second object in array" , "inner array" : [ { <object> } , { <object> } ] } ]
To parse the above you need two nested for loops (or something recursive).
Method 2
[ { "name" : "first object in array" , "first inner object" : { <object> } , "second inner object" : { <object> } } , <etc.> ] } ]
The second method can be parsed with a single for loop because you know in advance the number of inner objects to expect.
I have a json :
[ {user:"John",s:"Ldh",e:"usa"},{user:"Paul",s:"bukit panjang ",e:"FedExForum - Memphis"},{user:"ross",s:"bukit panjang ",e:"FedExForum - Memphis "}]
I am parsing this with the following code to retrieve all the values of "user" ..
public class ListViewAndroidActivity extends ListActivity {
private String newString, user;
ArrayList<String> results = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestServiceActivity test = new TestServiceActivity(); //This returns json from the server
newString = test.readPooledFeed(); // returned json in string format
JSONArray rootArray = new JSONArray(newString);
int len = rootArray.length();
for(int i = 0; i < len; ++i) {
JSONObject obj = rootArray.getJSONObject(i);
user = obj.optString("user");
results.add(user);
}
}
This gives me no error.. but nothing is shown on the screen .. kindly help!
optString : Get an optional string associated with a key.
I don't see the key u in your JSON object, shouldn't it be user = obj.optString("user");
JSON formatting
Your JSON data is not valid, it's valid as javascript, but not as JSON.
All properties should be quoted in JSON:
[
{ "user": "John", "s": "Ldh", "e": "usa"},
{ "user":"Paul", "s":"bukit panjang ", "e": "FedExForum - Memphis" },
{ "user": "ross", "s":"bukit panjang ", "e":"FedExForum - Memphis "}
]
Indentation is not needed, I just did it to make it clearer.
Missing field
Your parser seems to ignore that your input data is invalid. Other problem could be as others mentioned you're requesting the u property at user = obj.optString("u"); which does not exists.