i_me_mine
i_me_mine

Reputation: 1433

Parse JSON with unknown data using Android

I am pulling all the values of an assessment's questions and answers out of two tables that have auto generated table names and column names. They are made server side with .csv files. It's pretty bad but I found a way using SELECT * statements in PHP. Anyways in my PHP file I have two arrays, questions and answers. I combine them and make a JSON Array like this

try {
    $success = 1;

    if (!empty($questions) && !empty($answers)) {
        $combo = array_combine($questions, $answers);       
        // success
        echo $success;
        // echoing JSON response
        echo json_encode($combo);   

    } else {
        $response["success"] = 0;          
        echo json_encode($response);
    }   
} catch (PDOException $e) {
    die($e->getMessage());
}

Now the JSON comes out as desired like this

{
    "1": "4",
    "Store #": " 0560",
    "How many microwave circuits did you run?": " 3",
    "How many new ovens did you deliver to the store?": " 1",
    "How many new racks did you deliver to the store?": " 5",        
    ...
    ...
}

The left side of the : contains the question and the right contains the answer. Just like I wanted.

The problem is my app will never know how much data this JSON Array will have or what will be inside it. So using my normal method of parsing this info will not work. I would under normal circumstances use something like this

class Load extends AsyncTask<String, Void, String> {

protected void onPreExecute() {
//progress bar etc
....
}

protected String doInBackground(String... args) {
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);

if (success == 1) {
    Log.v("RESPONSE", "Success!");
    // products found: getting Array of Questions
    questions = json.getJSONArray(TAG_QUESTIONS);

    // looping through All Questions
    for (int i = 0; i < questions.length(); i++) {

        JSONObject c = questions.getJSONObject(i);

        // Storing each JSON item in variable
        String name = c.getString(TAG_NAME);
        String field = c.getString(TAG_FIELD);
        String value = c.getString(TAG_VALUE);

        // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();

        // adding each child node to HashMap key => value
        map.put(TAG_NAME, name);
        map.put(TAG_FIELD, field);
        map.put(TAG_VALUE, value);

        infoList.add(map);
}
....

This however requires you to set some sort of identifier for your tags in PHP and/or know whats coming across so you can tell the code how to parse the Strings etc.

So can you parse JSON with unknown data? If so, how? Thanks in advance

EDIT

I'm working on what I think is a solution but I need some help. Here is the code I'm using inside doInBackground()

try {
    // Checking for SUCCESS TAG
    int success = json.getInt(TAG_SUCCESS);

    if (success == 1) {
    info = json.getJSONArray(TAG_INFO);
    for (int i = 0; i < info.length(); i++) {
        if (info != null) {
            for (int j = 0; j < info.length(); j++) {
                clientList.add(info.get(j).toString());
            }
        }
    }
                    for (String s : clientList) {
                        Log.v("CHECKING S", s);
                        s.split(":");
                        Log.v("CHECKING S SPLIT", s);
                        values.add(s);
                        Log.v("CHECKING VALUES 0", values.get(0));
                        mQuestions.add(values.get(0));
                        Log.v("CHECKING VALUES 1", values.get(1));
                        mAnswers.add(values.get(1));                        
                    }

                } 

But the response stays in JSON and does not split it at all.

The log.v Looks like this

06-27 23:26:03.419: V/CHECKING S SPLIT(32233): {"Were any of the steamers gas?":" yes","Voltage readings on Turbo Chef 4":" 34","Voltage readings on Turbo Chef 3":" 43","Voltage readings on Turbo Chef 2":" 54","Did you label all the outlets?":" yes","Voltage readings on Turbo Chef 1":" 64","How many new ovens did you deliver to the store?":" 1","If yes, did you cap the water lines?":" yes","Phone #":" (740) 389-1174","Has all new equipment been installed & have you confirmed it is all working properly?":" yes","How many new racks did you deliver to the store?":" 5","Are all oven circuits tied into electrical shut down for hood?":" yes","How many Back steamers did you remove?":" none","Date":" 6-24-13","Zip":" 43302","How many oven circuits did you run?":" 2","How many microwave circuits did you run?":" 3","If yes, did you cap the gas lines?":" yes","Did you remove the existing FRONT steamers?":" yes","Did you remove the existing BACK steamers?":" no","Voltage readings on microwave circuit 1":" 57","City":" Marion","Voltage readings on microwave circuit 3":" 92","If yes, how?  Shunt Tripp  or Contactor":" shunt tripp","Voltage readings on microwave circuit 2":" 87","How many front steamers did you remove?":" 2","1":"4","State":" OH","Store #":" 0560","How many existing steamers did you remove for disposal off-site?":" none","Address":" 1318 Mount Vernon Avenue","Tech Name":" Jon Doe"}

They all look like this, none of them are split and they are still in JSON form. Any ideas?

Upvotes: 0

Views: 163

Answers (3)

Rico Harisin
Rico Harisin

Reputation: 3409

i think the problem is you only parse JSON array once instead twice

you need to parse the JSON array for the second time to parse question - answer list

try {
    // Checking for SUCCESS TAG
    int success = json.getInt(TAG_SUCCESS);

    if (success == 1) {
    info = json.getJSONArray(TAG_INFO);
    for (int i = 0; i < info.length(); i++) {
        if (info != null) {
            //parse JSON Array for the second time to parse question - answer
            JSONArray jarray = new JSONArray(info.getString(i));
            for (int j = 0; j < jarray.length(); j++) {
                clientList.add(jarray.getString(j));
            }
        }
    }

Upvotes: 0

Rico Harisin
Rico Harisin

Reputation: 3409

i don't know about php, but i can achieve something like that in perl using key value

you can read here for more info about key value in php, hope it can help you http://php.net/manual/en/language.types.array.php

Upvotes: 0

Ray
Ray

Reputation: 468

I think you could change the structure of json which you returned.

Maybe like the blow

{
    "1": "4",
    "Store #": " 0560",
    "How many microwave circuits did you run?": " 3",
    "How many new ovens did you deliver to the store?": " 1",
    "How many new racks did you deliver to the store?": " 5",        
    ...
    ...
}

to

{
    questions: [
        {
            question: "1",
            answer: "4"
        },
        {
            question: "Store",
            answer: "0560"
        },
        {
            question: "How many microwave circuits did you run",
            answer: "3"
        },
        {
            question: "How many new ovens did you deliver to the store?",
            answer: "1"
        },
        {
            question: "How many new racks did you deliver to the store?",
            answer: "5"
        }
    ]
}

and parse json as jsonarray

Upvotes: 2

Related Questions