Getting JSON values from a .json - java

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

Related

Get specific value from JSON array using 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");

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!
}
}

HTTPResponse as JSON in Java

I was trying to get an JSONObject from a HTTP response.
try
{
GetMethod postMethod = new GetMethod();
postMethod.setURI(new URI(url, true));
postMethod.setRequestHeader("Accept", "application/json");
httpClient.executeMethod(postMethod);
String resp=postMethod.getResponseBodyAsString();
org.json.JSONTokener tokener = new org.json.JSONTokener(resp);
finalResult = new org.json.JSONArray(tokener);
return finalResult;
}
But I got a runtime warning as
Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
Should I get the response as stream as suggested by the JVM ? If so, how could I parse the JSON from it ?
Has your server been set up to inform clients how big its responses are? If not, your server is streaming the data, and it's technically impossible to tell how much buffer space is required to deal with the response, warranting a warning that something potentially dangerous is going on.
if you want to send jsonObjects from server suppose (tomcat server)
For server side-
creating jsonobjects-
I have Called toJson() for creating jsonobjects this is the implementation-
final JSONObject arr = new JSONObject();
for (int i = 0; i < contactStatus.size(); i++) {
ContactStatus contactObject = contactStatus.get(i);
try {
arr.put(String.valueOf(i), toJson(value1, value2,, value3));
} catch (JSONException e) {
catch block e.printStackTrace();
}
}
//Here we serialize the stream to a String.
final String output = arr.toString();
response.setContentLength(output.length());
out.print(output);//out is object of servlet output stream.
public static Object toJsonForContact(String value1, boolean value2, double value3) throws JSONException {
JSONObject contactObject = new JSONObject();
contactObject.put("id", id);
contactObject.put("status", value1);
contactObject.put("distance", value2);
contactObject.put("relation", value3);
return contactObject;
}
so your jsonobjects are ready for sending we write these objects to ServletoutputStream.
in client side-
while ((ReadResponses = in.readLine()) != null) {
Constants.Response_From_server = ReadResponses;
if (Constants.Response_From_server.startsWith("{")) {
ListOfContactStatus = new ArrayList<ContactStatus>();
ContactStatus contactStatusObject;
try {
JSONObject json = new JSONObject(Constants.Response_From_server);
for (int i = 0; i < json.length(); i++) {
contactStatusObject = new ContactStatus();
JSONObject json1 = json.getJSONObject(String.valueOf(i));
System.out.println("" + json1.getString("id"));
System.out.println("" + json1.getBoolean("status"));
System.out.println("" + json1.getDouble("distance"));
contactStatusObject.setId(json1.getString("id"));
contactStatusObject.setStatus(json1.getBoolean("status"));
contactStatusObject.setDistance((float) json1.getDouble("distance"));
ListOfContactStatus.add(contactStatusObject);
System.out.println("HTTPTransport:sendMessage Size of ListOfContactStatus" + ListOfContactStatus.size());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You can easily generate JSonObject usin Java EE 7. The sample code.
JsonReader reader = Json.createReader(new URI(url, true));
JsonObject jsonObject=reader.readObject();
For details information go through to the link.
http://docs.oracle.com/javaee/7/tutorial/doc/jsonp003.htm#BABHAHIA

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