How to acess the following property in this Json - JAVA - java

I have the following code that get the JSON in this URl :
https://www.googleapis.com/youtube/v3/search?key=AIzaSyCg3WitBUQl5ifC2QygQaZUPOSRMKfSD5E&channelId=UCPSDAF3Htm3AIxw4OUM3Lew&part=snippet,id&order=date&maxResults=20
I can acess the propierty "nextPageToken" and get your value with the following code:
JSONObject json = readJsonFromUrl(
"https://www.googleapis.com/youtube/v3/search?key=AIzaSyCg3WitBUQl5ifC2QygQaZUPOSRMKfSD5E&pageToken="
+ nextPageToken + "&channelId=" + new GetListAndPLayListYoutube().getIdUsuario()
+ "&part=snippet,id&order=date&maxResults=50");
System.out.println(json.get("nextPageToken"));
But i try Acess the property inside of "items" what is "videoId" and get the value of videoId, but not work, how can get the value of videoId

Try below code to get videoid from json String.
pass your json string object from parseJson() method:
private void parseJson(String responseString){
try {
Object object = new JSONTokener(responseString).nextValue();
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
Object object1 = jsonArray.getJSONObject(i);
if (object1 instanceof JSONObject) {
JSONObject jsonObject1 = (JSONObject) object1;
JSONObject jsonObject2= jsonObject1.optJSONObject("id");
String videoId = jsonObject2.optString("videoId");
System.out.println("videoId=" + videoId);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

It looks like you querying Youtube's Search API and extracting results from response. In which case, I would recommend using Google's API Client library (here) for Java instead of writing your own implementation.
Here are some examples of how to search Youtube using Google's API client and retrieve video information.

Related

Access intended values in JSON file using JAVA

This is the JSON file I am working with
{"sentiment":
{"document":
{
"label": "positive",
"score": 0.53777
}
}
}
I need to access the value in label and score. using java. How can I do that?
Find below the code I am using right now:
JSONParser parser = new JSONParser();
try
{
Object object = parser
.parse(new FileReader("output_nlu_sentiment.json"));
//convert Object to JSONObject
JSONObject jsonObject = new JSONObject();
JSONObject sentimentobject= new JSONObject();
JSONObject documentobject = new JSONObject();
sentimentobject= (JSONObject) jsonObject.get("sentiment");
documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
//float score = (float) jsonObject.get("score");
System.out.println(label);
String test = (String) sentimentobject.get("label");
System.out.println(test);
} catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
Why is it printing the value as null.
You might want to have a look at JacksonXml for json parsing.
Right now the problem is that you're not using the JsonObject returned by parser.parse(...).
Instead you use the get method on objects you just created. This of course means that you don't getthe valie you want to.
Try to use following code (JSONObject jsonObject = (JSONObject) object instead of JSONObject jsonObject = new JSONObject();), because you didn't use object at all, just create new empty JSONObject.
JSONParser parser = new JSONParser();
try
{
Object object = parser
.parse(new FileReader("output_nlu_sentiment.json"));
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
JSONObject sentimentobject = (JSONObject) jsonObject.get("sentiment");
JSONObject documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
System.out.println(label);
float score = (float) documentobject.get("score");
System.out.println(score );
}catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
You have to make use of object created in Object object = parser.parse(new FileReader("output_nlu_sentiment.json")); while creating the jsonObject
For that you can look at the code below:
Object object = parser
.parse(new FileReader("file2.json"));
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
JSONObject sentimentobject= new JSONObject();
JSONObject documentobject = new JSONObject();
sentimentobject= (JSONObject) jsonObject.get("sentiment");
documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
//float score = (float) jsonObject.get("score");
System.out.println(label);
String test = (String) sentimentobject.get("label");
You will get the positive printed on console.
you should see the content in para 'sentimentobject',force convert into class JSONObject can not get the value you want.
I prefer the FasterXML Jackson support to parse JSON into plain old Java objects (POJOs). These POJOs are often called Data Transfer Objects (DTOs) and give you a way to turn your JSON fields into properly typed members of the corresponding DTO.
Here is an example method to do that. The ObjectMapper(s) are generally maintained as statics somewhere else because FasterXML's implementation caches information to improve efficiency of object mapping operations.
static final ObjectMapper mapper = new ObjectMapper();
This is the JSON deserialization method:
public static <T> T deserializeJSON(
final ObjectMapper mapper, final InputStream json,
final Class<T> clazz)
throws JsonParseException, UnrecognizedPropertyException,
JsonMappingException, IOException
{
final String sourceMethod = "deserializeJSON";
logger.entering(sourceClass, sourceMethod);
/*
* Use Jackson support to map the JSON into a POJO for us to process.
*/
T pojoClazz;
pojoClazz = mapper.readValue(json, clazz);
logger.exiting(sourceClass, sourceMethod);
return pojoClazz;
}
Assuming I have a class called FooDTO, which has the appropriate Jackson annotations/getters/setters (note you must always provide a default empty public constructor), you can do this:
FooDTO foo = deserializeJSON(mapper, inputstream, FooDTO.class);
The deserialization throws a few different exceptions (all of which have IOException as their parent class) that you will need to handle or throw back to the caller.
Here besides of the correction alreay addressed in comments and other answers, I include some other changes you can benefit of:
It is not necessary to initialize the JSONObjects with a new instance that is going to be ovewritten in the next line.
You can use getJSONObject(), getString(), getFloat() instead of get(), in this way you don't need to cast the result.
public void parseJson() {
JSONParser parser = new JSONParser();
try
{
JSONObject jsonObject = new JSONParser().parse(new FileReader("output_nlu_sentiment.json"));
JSONObject sentimentobject= null;
JSONObject documentobject = null;
sentimentobject= jsonObject.getJSONObject("sentiment");
documentobject= sentimentobject.getJSONObject("document");
String label = documentobject.getString("label");
float score = documentobject.getFloat("score");
String output = String.format("Label: %s Score: %f", label, score);
System.out.println(output);
}catch(FileNotFoundException fe){
fe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
Also for this kind of objects, where the attribute names could act as object properties, I suggest you take a look at Gson library. After modeling the json as a composition of POJOs, the parsing takes 1 line of code.

How to get the fields of a JSON object in android studio?

I have an android app and a Web Service. When I want to edit some register I have to get the whole record from the database and put every field in a Edit Text.
The Web Service return me this to the android app
[{"id":"6","0":"6","tipo":"No Oxidado","1":"No Oxidado","fecha":"2015-02-02","2":"2015-02-02","ubicacion":"-1.555505, -6.6171","3":"-1.555505, -6.6171","persona":"Laura Morales","4":"Laura Morales","fotografia":"-","5":"-"}]
And I have a variable called "result" that have this JSON string
How do I put every field in a independent edit text in my Android App?
something like:
txtid.setText(result[0]);
txtType.setText(result[1]);
txtDate.setText(result[2]);
txtLocation.setText(result[3]);
txtPerson.setText(result[4]);
where "result" is my JSON string.
try below code.
if you have more than one json object in array
String response = "[{"id":"6","0":"6","tipo":"No Oxidado","1":"No Oxidado","fecha":"2015-02-02","2":"2015-02-02","ubicacion":"-1.555505, -6.6171","3":"-1.555505, -6.6171","persona":"Laura Morales","4":"Laura Morales","fotografia":"-","5":"-"}]"
try {
JSONArray jsonArray = new JSONArray(response);
for (int i =0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
txtid.setText(jsonObject.getString("0"));
txtType.setText(jsonObject.getString("1"));
txtDate.setText(jsonObject.getString("2"));
}
} catch (JSONException e) {
e.printStackTrace();
}
And if you have only one object in array then no need to use for loop use directly this way
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
txtid.setText(jsonObject.getString("0"));
txtType.setText(jsonObject.getString("1"));
txtDate.setText(jsonObject.getString("2"));
} catch (JSONException e) {
e.printStackTrace();
}
there is a library to convert Json object to android model that call GSON
at first create a model with your input object like below:
class InputModel {
String id;
String 0; //it's better to change this object name
String tipo;
...
}
next, you can use Gson to bind your input to your model. it should be something like this:
InputModel mInput = new Gson().fromJson(data);
ps1: data is your input string
ps2: if you want the name of your input be different with your input name, you can use an annotation like this:
#SerializedName("id")
String productId;

Dynamic JSON issue

My JSON Structure will vary depend on the request. But the content inside each element remain same. For Example:
JSON1:
{
"h1": {
"s1":"s2"
},
"c1": {
"t1:""t2"
}
}
JSON2:
{
"h1": {
"s1":"s2"
},
"c2": {
"x1:""x2"
}
}
In the above example, elements inside h1,c1 and c2 are constant. Please let me know how to convert JSON to JAVA Object
Regards
Udhaya
First of all You need to understand Json Structure cause above format is incorrect visit this
and this
And you can use Google Gson or Json for parsing the result json String .
"t1:""t2" json format incorrect
Used
"t1":"t2"
Instead of
"t1:""t2"
and also used
"x1": "x2"
Instead of
"x1:""X2"
Code to take in java
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonsubObject = jsonObject.getJSONObject("h1");
String s1 = jsonsubObject.getString("s2");
JSONObject jsonsubObject1 = jsonObject.getJSONObject("c1");
String t1 = jsonsubObject1 .getString("t2");
}
catch (JSONException e) {
e.printStackTrace();
}
Use Google Gson:
Gson gson = new Gson();
ClassName object;
try {
object = gson.fromJson(json, ClassName.class);
} catch (com.google.gson.JsonSyntaxException ex) {
//the json wasn't valid json
}
String validJson = gson.toJson(obj); //obj is an instance of any class
json must be a valid JSON String
import org.json.JSONObject;
you can simple pass your data in constructor of JSONObject it automatically handle, you need to throws JSONException which may occur during conversion id format of data is not correct
String data = "{'h1':{'s1':'s2'},'c1':{'t1:''t2'}}";
JSONObject jsnobject = new JSONObject(data);

Gson JsonObject copy value affected others JsonObject instance

I have weird problem with gson (my gson version is 2.3.1)
I have JsonObject instance called jsonObject (JsonObject jsonObject)
jsonObject has value, not empty
And I create another one, JsonObject tempOject = jsonObject;
So, when I try to remove element inside tempObject, lets say,
tempObject.remove("children");
Then that code affected the jsonObject instance.
Here is the code snippet :
jsonObject = element.getAsJsonObject();
JsonElement tempElement = element;
JsonObject tempObject = jsonObject;
String tempJson;
if(tempObject.has("children")){
tempObject.remove("children");
tempJson = tempObject.toString();
tempElement = new JsonParser().parse(tempJson);
}
if(nodes.isEmpty()){
elements = new ArrayList<>();
nodes.put(iterator, elements);
}
if(!nodes.containsKey(iterator)){
elements = new ArrayList<>();
nodes.put(iterator, elements);
}
nodes.get(iterator).add(tempElement);
if (jsonObject.has("children")){
tempNextJson = jsonObject.get("children").toString();
tempCurrJson = jsonObject.toString();
tempIterator++;
metaDataProcessor(tempNextJson, tempCurrJson, tempNextJson, tempIterator, maxLevel);
}
I have read the gson JsonObject class, it use deep copy method. That was not supposed to affected the reference since JsonObject using deep value copy, so the returned JsonObject object is the new one.
But why this is happened?
Anyway...there is deepCopy method inside JsonObject class
JsonObject deepCopy() {
JsonObject result = new JsonObject();
Iterator i$ = this.members.entrySet().iterator();
while(i$.hasNext()) {
Entry entry = (Entry)i$.next();
result.add((String)entry.getKey(), ((JsonElement)entry.getValue()).deepCopy());
}
return result;
}
But thats an abstract method from JsonElement class which implemented on JsonObject, and the attribute not set as public, so I cannot call that method. But I guess that method supposedly called directly when I do instance copy.
How about that?
Thanks in advance
This can be used to copy any object of any type!
just have to use Gson.
public <T> T deepCopy(T object, Class<T> type) {
try {
Gson gson = new Gson();
return gson.fromJson(gson.toJson(object, type), type);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
in your case you can call it like:
JsonObject jsonObject = deepCopy(oldJsonObject, JsonObject.class);
Starting from version 2.8.2, deepCopy() in Gson JsonElement is public, so you can now use it to make a deep copy of your JSON object.
Setting tempObject = jsonObject will not create a second object for you. All that does is create another reference to your original jsonObject.
What you want to do is something like:
JSONObject tempObject = new JSONObject(jsonObject.toString());
tempObject.remove("children");
This will create a new JsonObject which is a copy of the original json you had.
If you can only use the GSON libraries, there is the JsonObject.deepyCopy() method. Which was added in r855: https://code.google.com/p/google-gson/source/detail?r=855
Using the deepCopy() method it would be
JsonObject tempObject = jsonObject.deepCopy();
tempObject.remove("children");
Looks like Gson developers decided not to expose deepCopy(). You could serialize your JsonElement this into a string and back, however, I think it's far more efficient to implement deep cloning outside of JsonObject instead. Here's my solution to this:
#Nonnull
public static JsonObject deepCopy(#Nonnull JsonObject jsonObject) {
JsonObject result = new JsonObject();
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
result.add(entry.getKey(), deepCopy(entry.getValue()));
}
return result;
}
#Nonnull
public static JsonArray deepCopy(#Nonnull JsonArray jsonArray) {
JsonArray result = new JsonArray();
for (JsonElement e : jsonArray) {
result.add(deepCopy(e));
}
return result;
}
#Nonnull
public static JsonElement deepCopy(#Nonnull JsonElement jsonElement) {
if (jsonElement.isJsonPrimitive() || jsonElement.isJsonNull()) {
return jsonElement; // these are immutables anyway
} else if (jsonElement.isJsonObject()) {
return deepCopy(jsonElement.getAsJsonObject());
} else if (jsonElement.isJsonArray()) {
return deepCopy(jsonElement.getAsJsonArray());
} else {
throw new UnsupportedOperationException("Unsupported element: " + jsonElement);
}
}
I have found the simplest solution for this. Since the deepCopy() method from JsonObject seems didn't work, then I just to make some transformation from JsonObject value to string and then transform to JsonElement with JsonParser().
Then make some new JsonObject from our new JsonObject. It seems more simple instead of create some helper method which is needs to reimplement the deepCopy. If we reimplement the iteration must considered how deep the JsonObject is. Since JsonObject is hashmap (LinkedTreeMap), and the value is JsonElement, so it need to parse recursively through JsonElement.

How to decode in java a json representation of Google appengine Text

I have two appengine applications and am serving a string representation of a JSONObject from one and picking it up in the other. Every thing works well if I don't include a Text object in the JSON
Here is the specific part of the JSON object causing the trouble:
,\"text\":\u003cText: rthBlog 1\r\n\"If you don\u0027t learn from history you are doomed to repeat i...\u003e,
Here is how it looks like in string form:
< Text: rthBlog 1
"If you don't learn from history you are doomed to repeat i...>
Here are the relevant code placing the string in the data store [I am using json.simple]:
Text item_text = new Text("default text"); //it get filled by text longer than 500 char's
JSONObject j = new JSONObject();
j.put("text", item_text);
j.put("item_links", j_links);
item.setProperty("as_json", j.toJSONString());
datastore.put(item);
Here is the code retrieving it wrapping it in a JSONArray the array in a JSONobject and producing a String [I am using appengine json]:
JSONArray search_results = new JSONArray();
for(Entity e: items)
{
String j = (String) e.getProperty("as_json");
JSONObject jo;
if(j != null)
{
System.out.println(TAG + ".searchItems() string as json: " + j);
jo = new JSONObject();
jo.put("item", j);
search_results.add(jo);
}
}
JSONObject jo = new JSONObject();
jo.put("items", search_results);
return jo.toJSONString();
Here is the code picking it up [I am using appengine json]:
try
{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = (JSONArray) jsonObject.get("items");
JSONObject array_member = null;
JSONObject j;
for(int i=0; i<jsonArray.length(); i++)
{
array_member = jsonArray.getJSONObject(i);
System.out.println("array member" + array_member);
/*Text text = (Text)array_member.get("text"); //
System.out.println(text.getValue());*/
String s_item = array_member.getString("item");
System.out.println("item in string form: " + s_item);
j = new JSONObject(s_item); //This is the exception causing line
You need to be in control of your serialization and deserialization to and from JSON ...
meaning complex object are represented as simple text or numbers.
Here you are trying to serialize a complex object which is not what it is intended for. Make sure you serialize only the value the object is holding not the entire object.
A nice and very powerfull library enabling to fully take control of the serialization/deserialization process is Jackson.

Categories

Resources