0

I have a case where I need to store a location of each key value of json, so that for each key, it automatically fetches the location and gives the value for it from json.

Here, I have a location of the key 'vehicle_id' inside json 'car' assigned to a variable like:

String location="jresp.getJSONArray('cars').getJSONObject(0).getString('vehicle_id')"

How do I make it as a variable in JAVA such that this location fetches the value of vehicle_id for me from JSON? I need it like:

String value=jresp.getJSONArray('cars').getJSONObject(0).getString('vehicle_id');

so that it gives me a value. I've searched in net, but couldn't find it anywhere. Please help me!

7
  • 1
    Can't understand , String varibale = jresp.getJSONArray('cars').getJSONObject(0).getString('vehicle_id'); What u want ?? Commented Oct 17, 2018 at 16:13
  • I'm sorry that I was not clear. I've updated my question. @Chanky Commented Oct 17, 2018 at 16:23
  • I guess you want to use this String variable at some other place like method or other class? What is exactly the case? Commented Oct 17, 2018 at 16:27
  • 1
    You want at runtime to compile and interpret arbitrary code as part of a method? Convoluted and risky. Commented Oct 17, 2018 at 16:38
  • @DhaRmvEErsiNgh I've updated my question. Please check it. Commented Oct 17, 2018 at 16:42

1 Answer 1

1

Instead of having the complete statement as a variable like -

String location="jresp.getJSONArray('cars').getJSONObject(0).getString('vehicle_id')"

You could have 3 different variables like -

String jsonArray = "cars";//You might need to do some string processing to get these
int objSeq = 0;
String key = "vehicle_id";

Then you can definitely use it in your Java statement -

String value=jresp.getJSONArray(jsonArray).getJSONObject(objSeq).getString(key);
Sign up to request clarification or add additional context in comments.

3 Comments

Thats a great suggestion. But the problem with this is, we do not know whether the key is present inside a json array of a json object, or it is just inside a json object
If you are bound to get "jresp.getJSONArray('cars').getJSONObject(0).getString('vehicle_id')" such statements, you can have conditional value extraction. In case where location.indexOf("getJSONArray") < 0, you will have only 1 variable i.e - the key. Its not an array and the value would be a different statement accepting only a single key as String value = jsonObj.get(key);
@RajeevRajan Thanks alot! That helps me to find a proper way to satisfy all conditions! It really helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.