Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename key in JSONObject using java?

Tags:

java

json

I want to rename the keys of a JSON object using Java.

My input JSON is:

{  
    "serviceCentreLon":73.003742,
    "type":"servicecentre",
    "serviceCentreLat":19.121737,
    "clientId":"NMMC01" 
}

I want to change it to:

{  
    "longitude":73.003742,
    "type":"servicecentre",
    "latitude":19.121737,
    "clientId":"NMMC01" 
}

i.e. I want to rename "serviceCentreLon" to "longitude" and "serviceCentreLat" to "latitude". I am using the JSONObject type in my code.

like image 851
Puneet Purohit Avatar asked Mar 16 '15 06:03

Puneet Purohit


1 Answers

Assuming you're using the json.org library: once you have a JSONObject, why not just do this?

obj.put("longitude", obj.get("serviceCentreLon"));
obj.remove("serviceCentreLon");
obj.put("latitude", obj.get("serviceCentreLat"));
obj.remove("serviceCentreLat");

You could create a rename method that does this (then call it twice), but that's probably overkill if these are the only fields you're renaming.

like image 100
user253751 Avatar answered Sep 18 '22 21:09

user253751