Json Keys and Values fetch

How can i fetch keys and values from json, for example

   "result": {
        "id": "1",
        "name": "admin",
        "password": "admin123"
    }

How can i get id, name, password and put it in YailList
and get 1, admin, admin123.
that is for example maybe keys length not equal id, name, password maybe more or less that is for example only, same for values

  // Simple Get Json keys and values list
    @SimpleFunction
    public void Get(String data){
        try {
            JSONObject jsonObject = new JSONObject(data);
            if (jsonObject.has("result")) {
                JSONObject resultObject = jsonObject.getJSONObject("result");

                // Get an array of keys and values
                for (int i = 0; i > resultObject.length(); i++) {

                }

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OnGot();
                    }
                });
            } else {
                throw new YailRuntimeError("Error Fetch Data", "Get");
            }
        } catch (JSONException e){
            e.printStackTrace();
            throw new YailRuntimeError(e.getMessage(), "Get");
        }
    }


    @SimpleEvent
    public void OnGot(YailList keys, YailList values) {
        EventDispatcher.dispatchEvent(this, "OnGotRow", keys, values);
    }

Hope you understand what i mean.

I've made a small example on how to get a YailList of keys for your JSON dynamically.

image

Test.aix (4.6 KB)

Import these classes. The org.json library is available in App Inventor already, so you do not need the JAR library for it.

import com.google.appinventor.components.runtime.util.YailList;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONObject;

The actual code:

    @SimpleFunction(description = "GetKeys")
    public YailList GetKeys(String json) {
        // Get the JSONObject of the key "result".
        JSONObject object = new JSONObject(json);
        JSONObject result = object.getJSONObject("result");

        // Create a List for the output.
        List<String> output = new ArrayList<String>();

        // Iterate over every item in the JSONObject, and appends the keys to the list "output".
        Iterator<String> keys = result.keys();
        while (keys.hasNext()) {
            output.add(keys.next().toString());
        }

        // Returns a YailList version of the output.
        return YailList.makeList(output);
    }

I'll leave the GetValues part to you. Hint: change something in the while loop.

2 Likes

Thanks @Gordon_Lu but my question is for keys and values not kays only i tried this way before i post this topic and i don't found any way to get values too.
if you know how to get values too pls tell me. thanks :heart:

import java.util.Map.Entry;
import java.util.Set;
 
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
    // Simple Get Json keys and values list
    @SimpleFunction
    public void Get(String data){
        JsonObject resultObject = JsonParser.parseString(data).getAsJsonObject();

        Set<Map.Entry<String, JsonElement>> entries = resultObject.entrySet();
        List<String> keys = new ArrayList<>();
        List<String> values = new ArrayList<>();

        // Get an array of keys and values
        for (Map.Entry<String, JsonElement> entry : entries) {
            keys.add(entry.getKey());
            values.add(String.valueOf(entry.getValue()));
        }

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                OnGot(YailList.makeList(keys), YailList.makeList(values));
            }
        });

    }
    
    @SimpleEvent
    public void OnGot(YailList keys, YailList values) {
        EventDispatcher.dispatchEvent(this, "OnGot", keys, values);
    }

this is only way i got it, but it is not work i don't know why?

error:

Why are you using Gson?

I know. I said, all you need to change is this.

keys.next() is the key. Get the value of the key (using getString).

Thanks @Gordon_Lu now it is work fine, just you need to add try catch to you code
Final code:


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

  @SimpleFunction(description = "Get Keys")
  public YailList GetKeys(String json) {
    try {
      // Get the JSONObject of the key "result".
      JSONObject object = new JSONObject(json);
      JSONObject result = object.getJSONObject("result");

      // Create a List for the output.
      List<String> output = new ArrayList<>();

      // Iterate over every item in the JSONObject, and appends the keys to the list "output".
      Iterator<String> keys = result.keys();
      while (keys.hasNext()) {
        output.add(keys.next());
      }

      // Returns a YailList version of the output.
      return YailList.makeList(output);
    } catch (JSONException e) {
      // Handle JSON parsing error here, you can return an empty list or handle it as needed.
      e.printStackTrace();
      return YailList.makeEmptyList();
    }
  }



  @SimpleFunction(description = "Get Values")
  public YailList GetValues(String json) {
    try {
    // Get the JSONObject of the entire input JSON.
    JSONObject object = new JSONObject(json);

    // Get the JSONObject of the key "result" within the input JSON.
    JSONObject result = object.getJSONObject("result");

    // Create a List for the output.
    List<String> output = new ArrayList<>();

    // Iterate over every item in the "result" JSONObject and append the values to the list "output".
    Iterator<String> keys = result.keys();
    while (keys.hasNext()) {
      String key = keys.next();
      String value = result.getString(key);
      output.add(value);
    }

    // Returns a YailList version of the output.
    return YailList.makeList(output);
    } catch (JSONException e) {
      // Handle JSON parsing error here, you can return an empty list or handle it as needed.
      e.printStackTrace();
      return YailList.makeEmptyList();
    }
  }

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.