Unable to get json parsing for specific field name - java

I am working on Yahoo Finance. Trying to parse json data from a url, such as Google finance data.
I am fetching data into a string "str" and then parsing the json data to reach the name field inside resources.
the json data is :
{
"list":{
"meta":{
"type":"resource-list",
"start":0,
"count":1
},
"resources":[
{
"resource":{
"classname":"Quote",
"fields":{
"name":"Alphabet Inc.",
"price":"710.489990",
"symbol":"GOOGL",
"ts":"1452891600",
"type":"equity",
"utctime":"2016-01-15T21:00:00+0000",
"volume":"3833751"
}
}
}
]
}
}
I am trying to use this code, but it is not working - need to reach the "name" field:
str4 = Client.execute(httpget, responseHandler);
//str holds the json data given above- checked.
JSONObject str1 = new JSONObject(str4);
JSONObject list = str1.getJSONObject("list");
JSONArray resources = list.getJSONArray("resorces");
JSONObject fields = resources.getJSONObject(1);
str2 = fields.getString("name");

I notices three issues with your code:
you have one item in your JSONArray, so you should retrieve item 0, not item 1.
you misspelled the word resources in your code.
Also, I think you didn't retrieve the fields correctly. This should do it:
JSONObject str1 = new JSONObject(str4);
JSONObject list = str1.getJSONObject("list");
JSONArray resources = list.getJSONArray("resources");
JSONObject fields = resources.getJSONObject(0).getJSONObject("resource").getJSONObject("fields");
str2 = fields.getString("name");

Related

Parse only particular fields in JSON at once

I have a huge JSON but I only need to parse specific fields. I know paths to these fields so I decided to try JPath and it works but I want to parse all fields at once.
Let's say I have such JSON:
{
"data": [
{
"field1": 1,
"field2": 1,
...
"another_data": [ {
"required_field1": "1",
"required_field2": "2"
}
],
...
}
]
}
I want to get only required fields with these paths and map it to Java POJO:
$.data[*].another_data[*].required_field1
$.data[*].another_data[*].required_field2
So as a final result I want to have a list of Java objects, where the object contains required_field1 and required_field2.
UPD:
how it works now
I have a Java POJO that's a container
class RequiredInfo {
private String field1;
private String field2;
//constructor, setters, etc
}
I read JSON path 2 times by using JPath:
String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
List<String> reqFields1 = JsonPath.read(document, "$.data[*].another_data[*].required_field1");
List<String> reqFields2 = JsonPath.read(document, "$.data[*].another_data[*].required_field2")
and then I map it to my POJO
for (int i = 0; i < reqFields1.size(); i++) {
res.add(new RequiredInfo(reqFields1.get(i), reqFields2.get(i)));
}
bit I think there is a better way how I can do it
You can try by creating a JSON object and get data:
JSONObject yourJsonObject = (JSONObject) new JSONParser().parse(yourJson);
JSONObject data = (JSONObject) yourJsonObject.get("data");
JSONObject data0 = (JSONObject) data.get(0);
JSONObject another_data = (JSONObject) data0.get("another_data");
String required_field1 = another_data.get("required_field1").toString();
String required_field2 = another_data.get("required_field2").toString();
Now that you have values, you can add them in your POJOs.

How to get the values from keys in nested objects using only json-simple

I want to get only a specific value out of all the nested objects. In the application I just need the msg 3 which is inside another object messages.
I have tried it using JSONObject but it is not working for nested object. However It is working with just a single object means root object .
INPUT - {"name":"lola","messages":{"msg 1":"msg 2","msg 3":"msg 4"},"age":22}
String s = sc.nextLine();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json);
Object name = json.get("messages");
System.out.println(name);
JSONObject messageObject = (JSONObject) json.get("messages");
System.out.println(employeeObject);
//Get employee first name
String msg= (String) messageObject.get("msg3");
System.out.println(msg);
The Output:
{"msg 3":"msg 4","msg 1":"msg 2"}
{"msg 3":"msg 4","msg 1":"msg 2"}
null
The last nested object is not fetching in any way. Another thing is that the normal print of the string as a JSONObject gets changed. like the msg3 came before msg1.
In place of null - msg4 should be there.
Thanks in advance.
You are missing a space between "msg" and "3". By the way - you can do this easier, as such.
String s = sc.nextLine();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json);
System.out.println(json.get("message").get("msg 3"));

How to modify the JSON data and return the updated JSON data

We have a requirement to update the JSON data in middle and need to return the updated JSON data using java. Also it should support any type of JSON data.
ex:
Assume {object:{"color":"red","shape":"Triangle"}} is the JSON data and in this we need to update the shape value to Rectangle and we need to return the updated JSON data as below:
{object:{"color":"red","shape":"Rectangle"}}
For this we need to pass the element path ( which element we need to update) and updateText and JSON Data to the JAVA code.
here is the methodCall:
updateValue("object/shape", "Rectangle", "{object:{"color":"red","shape":"Triangle"}}")
We tried below code using Gson library. But with this code we are able to update the targeted Json element, but the requirement is to return the entire JSON data with the updated value.
So please suggest how do we re-build the JSON data with the updated text.
Below is the code we tried to update the Json Data.
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
String result = "";
for(String key : keys)
{
if (jsonObject.get(key) instanceof JsonObject)
{
jsonObject = (JsonObject)jsonObject.get(key);
}
else if(jsonObject.get(key) instanceof JsonArray)
{
JsonArray jsonArray = (JsonArray)jsonObject.get(key);
result = jsonArray.toString();
}
else
{
result = jsonObject.get(key).toString();
}
}
result = result.replace(result, updateText);
return result;
}
The problem lies in the way you do the replacements. When you translate the JsonObject to String, you lose the object, and after replacement, you just have the replaced String. To fix it, you need to operate directly on the object, instead of the String counterpart. Because JsonObject is mutable, holding a reference to the input will reflect the changes. One drawback is you can't replace a value in a JsonArray this way, partly because you don't know which element to replace. To accomplish that, you will need a little more in the input(either the value to replace or the element position).
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
JsonObject returnVal = jsonObject; // This holds the ref to target json object
JsonPrimitive jp = new JsonPrimitive(updateText);
String finalKey = keys[keys.length - 1];
for(String key : keys)
{
if (jsonObject.get(key).isJsonObject())
{
jsonObject = (JsonObject)jsonObject.get(key);
}
}
jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();
}
You can use JsonPath lib for that and try using the following code.
private static final Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
JsonNode updatedJson = JsonPath.using(configuration).parse(originaljson)
.set("use the path to go for value", "new value").json();
json = updatedJson.toString();

how to get the name of json object from my json array

I am trying to get the name of my json key from my jsonarray but not able to take in java.
[{"ParamName":"param1","DefaultValue":"","Hidden":"Hidden","LinkedParameter":"city"}]
I just want to take name of key like i only want to take "ParamName" and need to check
if (ParamName == "ParamName") {
Then do this.
}
You can convert this to JSON object.
JSONArray json = (JSONArray)new JSONParser().parse("[{\"ParamName\":\"param1\",
\"DefaultValue\":\"\",\"Hidden\":\"Hidden\",\"LinkedParameter\":\"city\"}]");
JSONObject obj= (JSONObject) json.get(0);
if("ParamName".equals(obj.get("ParamName"))){
}

JSON Parsing in Android (Flickr API)

I've been looking extract image urls from the Flickr api for my android application.
More specifically, I need to parse the first owner and first id field for the following JSON
http://pastebin.com/NVKXdELx
Hence, I tried
JSONObject json = new JSONObject(jsonString);
JSONObject photos = json.getJSONObject("photos");
JSONObject photo = photos.getJSONObject("photo");
String picOwner = photo.getString("owner");
String picID = photo.getString("id");
To me, the logic makes sense (grab the row photos, then grab the row photo, then extract the owner field as a string). However, an error is thrown on
JSONObject photo = photos.getJSONObject("photo");
Am I overlooking something?
Note: The ultimate values I am looking for are
"id": "8637130199",
"owner": "93693022#N07"
The element identified by "photo" is a JSON Array, you need to use the JSONArray class
JSONObject json = new JSONObject(jsonString);
JSONObject photos = json.getJSONObject("photos");
JSONArray photo = photos.getJSONArray("photo");
if (photo.length() > 0) {
JSONObject first = photo.getJSONObject(0);
String picOwner = first.getString("owner");
String picID = first.getString("id");
}

Categories