Get the key value from a json in Java - JSON Parsing - java

I have a json as below. I want to get mobile_number from this jsonObject.
json:-
{"id": "ABCD", "report": { "data": { "phone": { "mobile_number": 9876543210, "active": "Y", "content": null } } } }
I am doing it like this and it works fine but can someone help me with any other approach for it without getting every key.
JSONObject jsonObject = new JSONObject(json);
JSONObject report = getJSONObjectFromJson(jsonObject, "report");
JSONObject data = getJSONObjectFromJson(jsonObject, "data");
JSONObject phone = getJSONObjectFromJson(data, "phone");
long mobileNumber = getLongFromJson(phone, "mobile_number");
private Long getLongFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getLong(key) : null;
}
private JSONObject getJSONObjectFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getJSONObject(key) : null;
}

I've just dealing with the similar issue and decided to use JsonPath like this:
final DocumentContext jsonContext = JsonPath.parse(jsonString);
final Object read = jsonContext.read("$['report']['data']['phone']['mobile_number']");

You can use Jackson ObjectMapper.
try {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"id\": \"ABCD\", \"report\": { \"data\": { \"phone\": { \"mobile_number\": 9876543210, \"active\": \"Y\", \"content\": null } } } }";
JsonNode rootNode = mapper.readTree(jsonString);
JsonNode mobileNumber = rootNode.path("report").path("data").path("phone").path("mobile_number");
System.out.println("Mobile Number: " + mobileNumber.longValue());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

So there are lot of ways to do it but everything leads eventually to traversing the tree.
So to conclude all the approaches,
1. **Convert string to JsonObject and traverse.**
JSONObject jsonObject = new JSONObject(json);
JSONObject report = getJSONObjectFromJson(jsonObject, "report");
JSONObject data = getJSONObjectFromJson(jsonObject, "data");
JSONObject phone = getJSONObjectFromJson(data, "phone");
long mobileNumber = getLongFromJson(phone, "mobile_number");
private Long getLongFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getLong(key) : null;
}
private JSONObject getJSONObjectFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getJSONObject(key) : null;
}
2. **Using jackson objectMapper to get the JsonNode and then traverse.**
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode= mapper.readTree(json);
JsonNode mobileNumber = jsonNode.path("report").path("data").path("phone").path("mobile_number");
3. **Using gson jsonmapper to convert to map and then iterate the map.**
Gson gson = new Gson();
Map map = gson.fromJson(json, Map.class);

jsonObject.getJSONObject("x").getJSONObject("Y").getJSONObject("z");
Another route would be to leverage the ObjectMapper.

Related

Convert JSON string to json objects

I have a json string returning:
[{"TRAIN_JOURNEY_STAFF[],"ID":15,"EMAIL_ADDRESS":"jk#connectedrail.com","PASSWORD":"test","FIRST_NAME":"Joe","LAST_NAME":"Kevin","DATE_OF_BIRTH":"1996-04-20T00:00:00","GENDER":"Male","STAFF_ROLE":"Conductor","PHOTO":null},{new record..}]
There are several records here, I can't find a way to convert this json string to individual objects. I'm using the following to read in the data:
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
}
I've tried the simple json libary but the parser mixes up the string, Which is not ideal as I need to output the data to rows object by object to jtables.
Any help would be appreciated.
Solved it with the below with GSON. Many thanks everyone!
JsonElement jelement = new JsonParser().parse(response.toString());
JsonArray jarray = jelement.getAsJsonArray();
JsonObject jobject = jarray.get(0).getAsJsonObject();
System.out.println(jobject.get("FIRST_NAME"));
You can use something like this:
public class ObjectSerializer {
private static ObjectMapper objectMapper;
#Autowired
public ObjectSerializer(ObjectMapper objectMapper) {
ObjectSerializer.objectMapper = objectMapper;
}
public static <T> T getObject(Object obj, Class<T> class1) {
String jsonObj = "";
T userDto = null;
try {
jsonObj = objectMapper.writeValueAsString(obj);
userDto = (T) objectMapper.readValue(jsonObj, class1);
System.out.println(jsonObj);
} catch (JsonProcessingException jpe) {
} catch (IOException e) {
e.printStackTrace();
}
return userDto;
}
Pass your JSON Object to this method alogn with class name and it will set the JSON data to that respective class.
Note:
Class must have the same variables as in the JSON that you want to map with it.
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
see this
You can use Jackson to convert JSON to an object.Include the dependency :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Then make a POJO class to store the JSON .The pojo class should reflect the json string structure and should have appropriate fields to map the values(Here in sample code Staff.class is a pojo class).Then, by using ObjectMapper class you can convert the JSON string to a java object as follows :
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(response.toString(), Staff.class);
Another simple method to read a JSON string and convert it into an object is :
JSON String:
{
"lastName":"Smith",
"address":{
"streetAddress":"21 2nd Street",
"city":"New York",
"state":"NY",
"postalCode":10021
},
"age":25,
"phoneNumbers":[
{
"type":"home", "number":"212 555-1234"
},
{
"type":"fax", "number":"212 555-1234"
}
],
"firstName":"John"
}
public class JSONReadExample
{
public static void main(String[] args) throws Exception
{
// parsing file "JSONExample.json"
Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));
// typecasting obj to JSONObject
JSONObject jo = (JSONObject) obj;
// getting firstName and lastName
String firstName = (String) jo.get("firstName");
String lastName = (String) jo.get("lastName");
System.out.println(firstName);
System.out.println(lastName);
// getting age
long age = (long) jo.get("age");
System.out.println(age);
// getting address
Map address = ((Map)jo.get("address"));
// iterating address Map
Iterator<Map.Entry> itr1 = address.entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
// getting phoneNumbers
JSONArray ja = (JSONArray) jo.get("phoneNumbers");
// iterating phoneNumbers
Iterator itr2 = ja.iterator();
while (itr2.hasNext())
{
itr1 = ((Map) itr2.next()).entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
}
}
For reference:
https://www.geeksforgeeks.org/parse-json-java/
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
What you have basically is this :
[
{
"TRAIN_JOURNEY_STAFF":[
],
"ID":15,
"EMAIL_ADDRESS":"jk#connectedrail.com",
"PASSWORD":"test",
"FIRST_NAME":"Joe",
"LAST_NAME":"Kevin",
"DATE_OF_BIRTH":"1996-04-20T00:00:00",
"GENDER":"Male",
"STAFF_ROLE":"Conductor",
"PHOTO":null
},
{
}
]
You can use JSON constructor to serialize this array to an Array of JSONObjects.
Try looking for JSONObject and JSONArray classes in Java.
The constructor basically takes the stringified JSON (which you already have).

No serializer found for class org.json.JSON in dropwizard in API Response but Result is Coming in when am printing a return type

I am getting a result from the model in the list:
List<Chemtemporder> tempOrder = lcbuyerdao.getc2code(cart.toString());
In this tempOrder I am getting all the data, but I have to send this data in particular format. For that am using JSONObject and JSONArray. Process this result into like below
{"cart":
{"121212000002":[
{
"seller":"121212",
"scheme":"",
"schPer":0,
"Mrp":null,
"splRate":0,
"itemName":"* Gemer 0.5 Tab",
"itmvalue":0,
"c_seller_buyer_code":null,
"ItemName":"* Gemer 0.5 Tab",
"stock":null,
"maxqty":0,
"schQty":0,
"minqty":1,
"mfacName":"",
"n_rowid":0,
"image":"",
"schAlertFlag":0,
"mrp":null,
"c_pack":"1card",
"orderedQty":2,
"buyer":"000002",
"ptr":null,
"c_item_code":"40130",
"mfacCode":"",
"Stock":null
}
]
}
}
This format is coming when am printing return type but in the postman response am getting an error msg.
Postman response:
No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
my code in Resources (Controller) :
public JSONObject cartTest(CustdetailCart cart) {
String buyer;
String seller;
String sellebuyer ="";
final List<Cartdet> list = cart.getCustDetails();
JSONObject jsBody = new JSONObject();
for(Cartdet temp:list) {
buyer= temp.getBuyer_code();
seller = temp.getSeller_code();
sellebuyer = seller+buyer;
jsBody.put(sellebuyer, new JSONArray());
}
System.out.println("jsBody"+jsBody.toString());
List<Chemtemporder> tempOrder =lcbuyerdao.getc2code(cart.toString());
for(Chemtemporder tmp :tempOrder ) {
ObjectMapper mapperObj = new ObjectMapper();
mapperObj.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
buyer = tmp.getBuyer();
seller = tmp.getSeller();
sellebuyer = seller+buyer;
JSONArray selbuy = jsBody.getJSONArray(sellebuyer);
System.out.println("selbuy "+selbuy.toString());
try {
System.out.println("mapper"+mapperObj.writeValueAsString(tmp));
selbuy.put(new JSONObject(mapperObj.writeValueAsString(tmp)));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
JSONObject jsObj = new JSONObject();
jsObj.put("cart", jsBody);
System.out.println(jsObj);
return jsObj;
}
Something wrong in the code, but I didn't get that can anyone solve this problem.
I Solved my problem... Maybe it is useful to other's
Controller
public ObjectNode cartTest(CustdetailCart cart) throws JsonProcessingException {
String buyer;
String seller;
String sellebuyer = "";
String sellebuyer1 = "";
final List<Cartdet> list = cart.getCustDetails();
ObjectMapper mapper = new ObjectMapper();
ObjectNode jsBody = mapper.createObjectNode();
for(Cartdet temp:list) {
buyer= temp.getBuyer_code();
seller = temp.getSeller_code();
sellebuyer = seller+buyer;
sellebuyer1 += seller+buyer+",";
jsBody.set(sellebuyer,mapper.createArrayNode());
System.out.println(jsBody);
}
List<String> c_seller_buyer_code = Arrays.asList(sellebuyer1.split("\\s*,\\s*"));
List<Chemtemporder> tempOrder =lcbuyerdao.getc2code(c_seller_buyer_code);
for(Chemtemporder tmp :tempOrder ) {
buyer = tmp.getBuyer();
seller = tmp.getSeller();
sellebuyer = seller+buyer;
ArrayNode orders = (ArrayNode) jsBody.get(sellebuyer);
try {
orders.add(mapper.readTree(mapper.writeValueAsString(tmp)));
} catch (IOException e) {
e.printStackTrace();
}
}
ObjectNode node = mapper.createObjectNode();
node.set("cart", jsBody);
return node;
}

Android: How to get JSON object keys from this json:

This is the JSON array:
{
"server_response": [{
"Total": "135",
"Paid": "105",
"Rest": "30"
}]
}
So, how can i get the object names? I want to put them in separate TextView.
Thanks.
Put this out side everything. I mean outside onCreate() and all.
private <T> Iterable<T> iterate(final Iterator<T> i){
return new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return i;
}
};
}
For getting the names of objects :
try
{
JSONObject jsonObject = new JSONObject("{" +"\"server_response\": [{" +"\"Total\": \"135\"," +"\"Paid\": \"105\"," +"\"Rest\": \"30\"" +"}]"+"}";);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject object = jsonArray.getJSONObject(0);
for (String key : iterate(object.keys()))
{
// here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
Toast.makeText(HomeActivity.this, ""+key, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps :)
My suggestion:
Go to this website:
Json to pojo
Get your pojo classes and then use them in Android.
All you need to do is to use Gson.fromGson(params here).
One of your params is the class that you created using the online schema.
You can use jackson ObjectMapper to do this.
public class ServerResponse {
#JsonProperty("Total")
private String total;
#JsonProperty("Paid")
private String paid;
#JsonProperty("Rest")
private String rest;
//getters and setters
//toString()
}
//Now convert json into ServerResponse object
ObjectMapper mapper = new ObjectMapper();
TypeReference<ServerResponse> serverResponse = new TypeReference<ServerResponse>() { };
Object object = mapper.readValue(jsonString, serverResponse);
if (object instanceof ServerResponse) {
return (ServerResponse) object;
}
JSONObject jsonObject = new JSONObject("Your JSON");
int Total = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Total");
int Paid = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Paid");
int Rest = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Rest");

JSONObject with List to String to JsonNode

I convert JSONObject in string for parse it in JsonNode with jackson but i have a List in my JSONObject and when i parse it with a ObjectMapper i get this :
["{Property1 : value1, Property2 : value2}"]
And i can't call myJsonNodeObject.get(i).get("Property1") this is my problem.
I have tried to cast my List in JSONArray in my JSONObject but don't work.
resultAsJSONObject = new JSONObject();
resultAsJSONObject.put("Label", getMetricStatisticsResult.getLabel());
resultAsJSONObject.put("Datapoints", getMetricStatisticsResult.getDatapoints());
resultAsJSONObject.put("fromDate", fromDate.getTimeInMillis());
resultAsJSONObject.put("toDate", toDate.getTimeInMillis());
resultAsJSONObject.put("error", "");
resultAsString = resultAsJSONObject.toString();
mapper.readValue(resultAsString, MetricsData.class);
Assuming that you have a JSON string which you just want to change. Then you can use Jackson to parse it as a ObjecNode and then modify it. Here is an example:
public class JacksonModifyJson {
static final String JSON = "{\"name\":\"Bob\", \"age\":13}";
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final ObjectNode jsonNode = mapper.readValue(JSON, ObjectNode.class);
jsonNode.put("url", "example.com");
System.out.println(mapper.writeValueAsString(jsonNode));
}
}
Output:
{"name":"Bob","age":13,"url":"example.com"}
THis method is really easy and works too
try {
JSONObject jsonObject = new JSONObject(THESTRINGHERE);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonArray;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
// System.out.println(listdata);
} catch (Exception e) {
System.out.println(e.getMessage());
}

Java Append object to JSON

I would like to append JSON object to existing JSON array to get data structure like this.
"results":[
{
"lat":"value",
"lon":"value"
},
{
"lat":"value",
"lon":"value"
}
]
I'm trying to do it using the code in example, but unfortunately whole object is overriden everytime.
Log.i(AppHelper.APP_LOG_NAMESPACE, "POSITIONS AVAILABLE " + jsonDataString);
AppHelper helper = new AppHelper(ctx);
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
//putv given values to the JSON
valuesObject.put("lat", lat.toString());
valuesObject.put("lon", lon.toString());
valuesObject.put("city", city);
valuesObject.put("street", street);
valuesObject.put("date", helper.getActualDateTime());
valuesObject.put("time", helper.getActualDateTime());
list.put(valuesObject);
//mainObject.put("values", list);
mainObject.accumulate("values", list);
saveJsonData(ctx, mainObject.toString(),"positions");
How it should be right?
Put and accumulate everytime rewrite all previous values, but i would like to append this object:
{
"lat":"value",
"lon":"value"
},
Into results parent.
BTW: I would like to do it without GSON.
Thanks for any help..
There isnt any problem with your code. It does append
String jsonDataString = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("lat", "newValue");
valuesObject.put("lon", "newValue");
valuesObject.put("city", "newValue");
valuesObject.put("street", "newValue");
valuesObject.put("date", "newValue");
valuesObject.put("time", "newValue");
list.put(valuesObject);
mainObject.accumulate("values", list);
System.out.println(mainObject);
This prints {"values":[[{"date":"newValue","city":"newValue","street":"newValue","lon":"newValue","time":"newValue","lat":"newValue"}]],"results":[{"lon":"value","lat":"value"},{"lon":"value","lat":"value"}]}.
Isnt this what you are expecting?
With gson you can do like
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class AddJson {
public static void main(String[] args) {
String json = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
Gson gson = new Gson();
JsonObject inputObj = gson.fromJson(json, JsonObject.class);
JsonObject newObject = new JsonObject() ;
newObject.addProperty("lat", "newValue");
newObject.addProperty("lon", "newValue");
inputObj.get("results").getAsJsonArray().add(newObject);
System.out.println(inputObj);
}
}
Simple Approach
String jsonData = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }]}";
System.out.println(jsonData);
try {
JSONArray result = new JSONObject(jsonData).getJSONArray("results");
result.getJSONObject(0).put("city","Singapore");
jsonData = "{\"results\":"+result.toString()+"}";
System.out.println(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
OutPut Before Appending
{"results":[{"lat":"value","lon":"value" }]}
OutPut After Appending
{"results":[{"lon":"value","lat":"value","city":"Singapore"}]}
If you want to add new value to an Object you can try the below as well
Before:
{
"Name": "EnCoMa",
"Manager": "Abhishek Kasetty"
}
code :
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(TheObjectToWhichYouWantToAddNewValue);
ObjectNode node = (ObjectNode) mapper.readTree(json);
node.putPOJO("new Key","new value")
after:
{
"Name": "EnCoMa",
"Manager": "Abhishek Kasetty",
"new Key": "new value"
}

Categories

Resources