Get specific value from JSON array using java - java

I want to fetch only PersonNumber value from below JSON sample using java.
{"Context":[{"PersonNumber":"10","DMLOperation":"UPDATE","PeriodType":"E","PersonName":"Ponce","WorkerType":"EMP","PersonId":"1000","PrimaryPhoneNumber":"1","EffectiveStartDate":"2018-01-27","EffectiveDate":"2018-01-27"}],"Changed Attributes":[{"NamInformation1":{"new":"Ponce","old":"PONCE"}},{"FirstName":{"new":"Jorge","old":"JORGE"}},{"LastName":{"new":"Ponce","old":"PONCE"}}]}
Below is my code:
for (SyndContentImpl content : (List<SyndContentImpl>) entry.getContents()) {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(content.getValue().toString());
System.out.println(jsonObj.get("Context"));
} catch (JSONException e) {
e.printStackTrace();
} }

You have to access to the path Context[0].PersonNumber.
This can be done with
String personNumber = jsonObj.getJSONArray("Context").getJSONObject(0).getString("PersonNumber");

Related

Getting JSON values from a .json

I am currently writing a program that pulls weather info from openweathermaps api. It returns a JSON string such as this:
{"coord":{"lon":-95.94,"lat":41.26},"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10n"}],"base":"stations","main": ...more json
I have this method below which writes the string to a .json and allows me to get the values from it.
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.get("weather"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}
The problem is it only allows me to get the outer values such as "coord" and "weather". So currently since I have System.out.println(Jobj.get("weather")); it will return [{"icon":"10n","description":"light rain","main":"Rain","id":500}] but I want to actually get the values that are inside of that like the description value and the main value. I haven't worked much with JSONs so there may be something obvious I am missing. Any ideas on how I would do this?
You can use JsonPath (https://github.com/json-path/JsonPath) to extract some json field/values directly.
var json = "{\"coord\":{\"lon\":\"-95.94\",\"lat\":\"41.26\"},\n" +
" \"weather\":[{\"id\":\"500\",\"main\":\"Rain\",\"description\":\"light\"}]}";
var main = JsonPath.read(json, "$.weather[0].main"); // Rain
you can use
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.getJSONObject("coord").get("lon");//here coord is json object
System.out.println(Jobj.getJSONArray("weather").get(0).get("description");//for array
or you can declare user defined class according to structure and convert code using GSON
Gson gson= new Gson();
MyWeatherClass weather= gson.fromJSON(Jobj .toString(),MyWeatherClass.class);
System.out.println(weather.getCoord());
From the json sample that you have provided it can be seen that the "weather" actually is an array of objects, so you will have to treat it as such in code to get individual objects from the array when converted to Jsonobject.
Try something like :
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject jobj = (JSONObject) obj;
JSONArray jobjWeatherArray = jobj.getJSONArray("weather")
for (int i = 0; i < jobjWeatherArray.length(); i++) {
JSONObject jobjWeather = jobjWeatherArray.getJSONObject(i);
System.out.println(jobjWeather.get("id"));
System.out.println(jobjWeather.get("main"));
System.out.println(jobjWeather.get("description"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}

How to check if a key exists in Json Object and get its value [duplicate]

This question already has answers here:
How to check if a JSON key exists?
(13 answers)
Closed 5 years ago.
Let say this is my JSON Object
{
"LabelData": {
"slogan": "AWAKEN YOUR SENSES",
"jobsearch": "JOB SEARCH",
"contact": "CONTACT",
"video": "ENCHANTING BEACHSCAPES",
"createprofile": "CREATE PROFILE"
}
}
I need to know that either 'video` exists or not in this Object, and if it exists i need to get the value of this key. I have tried following, but i am unable to get value of this key.
containerObject= new JSONObject(container);
if(containerObject.hasKey("video")){
//get Value of video
}
Use below code to find key is exist or not in JsonObject. has("key") method is used to find keys in JsonObject.
containerObject = new JSONObject(container);
//has method
if (containerObject.has("video")) {
//get Value of video
String video = containerObject.optString("video");
}
If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject.
Use:
if (containerObject.has("video")) {
//get value of video
}
From the structure of your source Object, I would try:
containerObject= new JSONObject(container);
if(containerObject.has("LabelData")){
JSONObject innerObject = containerObject.getJSONObject("LabelData");
if(innerObject.has("video")){
//Do with video
}
}
Please try this one..
JSONObject jsonObject= null;
try {
jsonObject = new JSONObject("result........");
String labelDataString=jsonObject.getString("LabelData");
JSONObject labelDataJson= null;
labelDataJson= new JSONObject(labelDataString);
if(labelDataJson.has("video")&&labelDataJson.getString("video")!=null){
String video=labelDataJson.getString("video");
}
} catch (JSONException e) {
e.printStackTrace();
}
containerObject = new JSONObject(container);
if (containerObject.has("video")) {
//get Value of video
}
Try
private boolean hasKey(JSONObject jsonObject, String key) {
return jsonObject != null && jsonObject.has(key);
}
try {
JSONObject jsonObject = new JSONObject(yourJson);
if (hasKey(jsonObject, "labelData")) {
JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
if (hasKey(labelDataJson, "video")) {
String video = labelDataJson.getString("video");
}
}
} catch (JSONException e) {
}
JSONObject class has a method named "has".
Returns true if this object has a mapping for name. The mapping may be NULL.
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
JSONObject root= new JSONObject();
JSONObject container= root.getJSONObject("LabelData");
try{
//if key will not be available put it in the try catch block your program
will work without error
String Video=container.getString("video");
}
catch(JsonException e){
if key will not be there then this block will execute
}
if(video!=null || !video.isEmpty){
//get Value of video
}else{
//other vise leave it
}
i think this might help you

How to return a from json converted array in java?

The following code works fine(!), i wnat to moved it into a own function, but i cant return the from json converted Array (last line). What im doing wronng?
public Array jsonToArray(String json) {
JSONObject myjson = null;
try {
myjson = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray the_json_array = null;
try {
the_json_array = myjson.getJSONArray("profiles");
} catch (JSONException e) {
e.printStackTrace();
}
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = null;
try {
another_json_object = the_json_array.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
arrays.add(another_json_object);
}
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
return Array jsons;
}
I think the Problem is the Type, but im completely new in JAVA... Im getting the error: 'Not a statement'. What is the meaning and the Solution?
public JSONObject[] jsonToArray()
As well as
return jsons;
Or, why not return the ArrayList<JSONObject>, why bother with another conversion?
Though, ideally, returning an actual JSONArray object instead of a Java array of JSONObject makes more sense.
Such as
return myjson.getJSONArray("profiles");
Or, one step further, actually parsing out the values of the JSON you want into your own Java classes?
You should do:
return jsons;
And also correct the return type, you have Array there, I don't see that type defined anywhere in your code, and there is no such type in java, you probably wanted JSONObject[], so the first line of the method will be:
public JSONObject[] jsonToArray(String json) {

Get first key and value from JSON object

I have JSON returned from my web server in the following form:
{"success":false,"errors":{"username":["Invalid username","Username too short"],"password":["Invalid password"]}}
How can I, in Java, parse the JSON to get the first key and the first value of that key? So in the above case, the output should be:
username
Invalid username
My current code looks like this:
String json = new String(((TypedByteArray) retrofitError.getResponse().getBody()).getBytes());
try {
JSONObject obj = new JSONObject(json);
String success = obj.getString("success");
JSONObject errors = obj.getJSONObject("errors");
// TODO
} catch (JSONException e) {
e.printStackTrace();
}
Perhaps something like this could help you, I'm not completely sure if I understand your problem:
for (final Iterator<String> iter = errors.keys(); iter.hasNext();) {
final String key = iter.next();
try {
final Object value = errors.get(key);
final JSONArray error = (JSONArray) value;
System.out.println(key);
System.out.println(error.get(0).toString());
} catch (final JSONException e) {
// Something went wrong!
}
}

GSON how to parse array with dynamic type

Looking at this Json file, KEY is always a String, but VALUE sometimes is a String but sometimes is an typed object with two String fields.
How can I parse it using GSON?
{
"property": [
{
"key": "key_A",
"value": "value_A"
},
{
"key": "key_B",
"value": "value_B"
},
{
"key": "key_C",
"value": {
"param_C_1": "value_C_1",
"param_C_2": "value_C_2"
}
}
]
}
The first thing is parsing this json file to java that can be done
this way :-
try {
InputStream is;
//read the whole json file stored in assets
//below is android way of opening file from local resource folder, you can use other means to open
is = getApplicationContext().getAssets().open("jsonfile.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
//convert the json file to string
String bufferString = new String(buffer);
JSONObject jsonObject;
JSONArray jsonArray;
jsonObject = new JSONObject(bufferString);
jsonArray=jsonObject.getJSONArray("property");
for (int i=0;i<jsonArray.length();i++){
jsonObject = jsonArray.getJSONObject(i);
JSONObject s = jsonArray.optJSONObject(i);
String s2 = s.getString("value");
if(s2.contains("{")){
JSONObject jobject = new JSONObject(s2);
String valueUnderValue1 = jobject.getString("param_C_1");
String valueUnderValue2 = jobject.getString("param_C_2");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Then make a class which will have all the values you got from the json file.
Say that class is MyClass, containing all of the values you got from json file.
make MyClass object and then
MyClass obj = new MyClass();
Gson gson = new Gson();
JSONObject onj = new JSONObject();
JSONArray userDataValues = new JSONArray();
//again convert to json
userDataValues.put(new JSONObject(gson.toJson(obj)));
//serialized the object
onj.put("property", userDataValues);
I hope this is what you want.

Categories

Resources