web-dev-qa-db-fra.com

Comment analyser une clé JSON dynamique dans un résultat JSON imbriqué?

J'ai un résultat JSON dans le format suivant qui JSON Lint montre cela comme une "réponse valide".

Ma question est: comment puis-je accéder au contenu de "question_mark" puisque "141", "8911", etc. sont toutes des valeurs dynamiques?

Mon exemple de code pour accéder à la valeur du "produit".

//Consider I have the first <code>JSONObject</code> of the "search_result" array and 
//I access it's "product" value as below.
String product = jsonObject.optString("product"); //where jsonObject is of type JSONObject.
//<code>product<code> now contains "abc".

JSON:

{
 "status": "OK",
 "search_result": [

            {
                "product": "abc",
                "id": "1132",
                "question_mark": {
                    "141": {
                        "count": "141",
                        "more_description": "this is abc",
                        "seq": "2"
                    },
                    "8911": {
                        "count": "8911",
                        "more_desc": "this is cup",
                        "seq": "1"
                    }
                },
                "name": "some name",
                "description": "This is some product"
            },
            {
                "product": "XYZ",
                "id": "1129",
                "question_mark": {
                    "379": {
                        "count": "379",
                        "more_desc": "this is xyz",
                        "seq": "5"
                    },
                    "845": {
                        "count": "845",
                        "more_desc": "this is table",
                        "seq": "6"
                    },
                    "12383": {
                        "count": "12383",
                        "more_desc": "Jumbo",
                        "seq": "4"
                    },
                    "257258": {
                        "count": "257258",
                        "more_desc": "large",
                        "seq": "1"
                    }
                },
                "name": "some other name",
                "description": "this is some other product"
            }
       ]
}

Le titre de ma question "clé dynamique" pourrait être faux mais je ne sais pas pour l'instant quel est le meilleur nom pour ce problème.

Toute aide serait grandement appréciée!

48
Sagar Hatekar

Utilisez JSONObject keys () pour obtenir la clé, puis répétez chaque clé pour obtenir la valeur dynamique.

En gros, le code ressemblera à:


    // searchResult refers to the current element in the array "search_result"
    JSONObject questionMark = searchResult.getJSONObject("question_mark");
    Iterator keys = questionMark.keys();

    while(keys.hasNext()) {
        // loop to get the dynamic key
        String currentDynamicKey = (String)keys.next();

        // get the value of the dynamic key
        JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);

        // do something here with the value...
    }

116
momo

Une autre possibilité est d'utiliser Gson (Remarque, j'utilise ici lombok pour générer des getters/setters, toString, etc.):

package so7304002;

import Java.util.List;
import Java.util.Map;

import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class JsonDemo {
    @Data
    private static class MyMap {
        private int count;

        @SerializedName("more_description")
        private String moreDescription;

        private int seq;
    }

    @Data
    private static class Product {
        private String product;

        private int id;

        @SerializedName("question_mark")
        private Map<String, MyMap> questionMark;
    }

    @Data
    private static class MyObject {
        private String status;

        @SerializedName("search_result")
        private List<Product> searchResult;
    }

    private static final String INPUT = ""; // your JSON

    public static void main(final String[] arg) {
        final MyObject fromJson = new Gson().fromJson(INPUT, 
            new TypeToken<MyObject>(){}.getType());
        final List<Product> searchResult = fromJson.getSearchResult();
        for (final Product p : searchResult) {
            System.out.println("product: " + p.getProduct() 
                + "\n" + p.getQuestionMark()+ "\n");
        }
    }
}

Sortie:

product: abc
{141=JsonDemo.MyMap(count=141, moreDescription=this is abc, seq=2), 
 8911=JsonDemo.MyMap(count=8911, moreDescription=null, seq=1)}

product: XYZ
{379=JsonDemo.MyMap(count=379, moreDescription=null, seq=5), 
 845=JsonDemo.MyMap(count=845, moreDescription=null, seq=6), 
 12383=JsonDemo.MyMap(count=12383, moreDescription=null, seq=4), 
 257258=JsonDemo.MyMap(count=257258, moreDescription=null, seq=1)}
13
user180100

La même chose peut également être faite en utilisant GSON, mais au lieu d'utiliser l'adaptateur de convertisseur GSON pour convertir en POJO. Nous allons l'analyser manuellement. Ce qui nous donne de la flexibilité en cas de données JSON dynamiques.
disons que le format JSON est comme ci-dessous dans mon cas.

{
  "dateWiseContent": {
    "02-04-2017": [
      {
        "locality": " Cross Madian Cross Rd No 4"
      }
    ],
    "04-04-2017": [
      {
        "locality": "Dsilva Wadi"
      },
      {
        "locality": " Cross Madian Cross Rd No 4",
        "appointments": []
      }
    ]
  }
}

dans ce cas, le dateWiseContent a clés d'objet dynamiques nous allons donc analyser ceci chaîne json utilisant la classe JsonParser.

  //parsing string response to json object
 JsonObject jsonObject = (JsonObject) new JsonParser().parse(resource);
  //getting root object
 JsonObject dateWiseContent = jsonObject.get("dateWiseContent").getAsJsonObject();

obtenir les clés dynamiques en utilisant Map.Entry<String, JsonElement> comme indiqué ci-dessous

  // your code goes here
         for (Map.Entry<String, JsonElement> entry : dateWiseContent.entrySet()) {

           //this gets the dynamic keys
            String  dateKey = entry.getKey();

            //you can get any thing now json element,array,object according to json.

            JsonArray jsonArrayDates = entry.getValue().getAsJsonArray();
            int appointmentsSize = jsonArrayDates.size();

             for (int count = 0; count < appointmentsSize; count++) {

                   JsonObject objectData = jsonArrayDates.get(count).getAsJsonObject();
                   String locality = objectData.get("locality").getAsString();


             }
        }

de même, n'importe quel niveau de json dynamique peut être analysé en utilisant Map.Entry<String,JsonElement>

0
vikas kumar

Un exemple d'utilisation de Google Gson

Données JSON de la question:

{
    "status": "OK",
    "search_result": [
        {
            "product": "abc",
            "id": "1132",
            "question_mark": {
                "141": {
                    "count": "141",
                    "more_description": "this is abc",
                    "seq": "2"
                },
                "8911": {
                    "count": "8911",
                    "more_desc": "this is cup",
                    "seq": "1"
                }
            },
            "name": "some name",
            "description": "This is some product"
        },
        {
            "product": "XYZ",
            "id": "1129",
            "question_mark": {
                "379": {
                    "count": "379",
                    "more_desc": "this is xyz",
                    "seq": "5"
                },
                "845": {
                    "count": "845",
                    "more_desc": "this is table",
                    "seq": "6"
                },
                "12383": {
                    "count": "12383",
                    "more_desc": "Jumbo",
                    "seq": "4"
                },
                "257258": {
                    "count": "257258",
                    "more_desc": "large",
                    "seq": "1"
                }
            },
            "name": "some other name",
            "description": "this is some other product"
        }
    ]
}

Exemple de code:

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class GsonExercise {
    public static void main(String[] args) {
        String jsonString = "{\"status\":\"OK\",\"search_result\":[{\"product\":\"abc\",\"id\":\"1132\",\"question_mark\":{\"141\":{\"count\":\"141\",\"more_description\":\"this is abc\",\"seq\":\"2\"},\"8911\":{\"count\":\"8911\",\"more_desc\":\"this is cup\",\"seq\":\"1\"}},\"name\":\"some name\",\"description\":\"This is some product\"},{\"product\":\"XYZ\",\"id\":\"1129\",\"question_mark\":{\"379\":{\"count\":\"379\",\"more_desc\":\"this is xyz\",\"seq\":\"5\"},\"845\":{\"count\":\"845\",\"more_desc\":\"this is table\",\"seq\":\"6\"},\"12383\":{\"count\":\"12383\",\"more_desc\":\"Jumbo\",\"seq\":\"4\"},\"257258\":{\"count\":\"257258\",\"more_desc\":\"large\",\"seq\":\"1\"}},\"name\":\"some other name\",\"description\":\"this is some other product\"}]}";
        JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class);
        JsonArray ja = jobj.get("search_result").getAsJsonArray();
        ja.forEach(el -> {
            System.out.println("product: " + el.getAsJsonObject().get("product").getAsString());
            JsonObject jo = el.getAsJsonObject().get("question_mark").getAsJsonObject();            
            jo.entrySet().stream().forEach(qm -> {
                String key = qm.getKey();
                JsonElement je = qm.getValue();
                System.out.println("key: " + key);
                JsonObject o = je.getAsJsonObject();
                o.entrySet().stream().forEach(prop -> {
                    System.out.println("\tname: " + prop.getKey() + " (value: " + prop.getValue().getAsString() + ")");
                });
            });
            System.out.println("");
        });
    } 
}

Sortie:

product: abc
key: 141
    name: count (value: 141)
    name: more_description (value: this is abc)
    name: seq (value: 2)
key: 8911
    name: count (value: 8911)
    name: more_desc (value: this is cup)
    name: seq (value: 1)

product: XYZ
key: 379
    name: count (value: 379)
    name: more_desc (value: this is xyz)
    name: seq (value: 5)
key: 845
    name: count (value: 845)
    name: more_desc (value: this is table)
    name: seq (value: 6)
key: 12383
    name: count (value: 12383)
    name: more_desc (value: Jumbo)
    name: seq (value: 4)
key: 257258
    name: count (value: 257258)
    name: more_desc (value: large)
    name: seq (value: 1)
0
Yuci