Varshini
Varshini

Reputation: 199

How can we convert a string to a working variable which fetch values in JAVA?

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!

Upvotes: 0

Views: 56

Answers (1)

Rajeev Ranjan
Rajeev Ranjan

Reputation: 4076

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);

Upvotes: 1

Related Questions