I have the following JSON text that I need to parse to get "id": 176514,
What is the required code?
{
"response": {
"count": 10307,
"items": [
{
"id": 176514,
"from_id": -114200945,
"owner_id": -114200945,
"date": 1506629224,
"marked_as_ads": 0,
"post_type": "post",
"text": "-я с разбитым сердцем сука,но я всё равно влюблённый.",
"post_source": {
"type": "api"
},
"comments": {
"count": 1,
"groups_can_post": true,
"can_post": 1
},
"likes": {
"count": 103,
"user_likes": 0,
"can_like": 1,
"can_publish": 1
},
"reposts": {
"count": 3,
"user_reposted": 0
},
"views": {
"count": 1022
}
}
]
}
}
I try some times but.. (
my code
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
class VK{
public static void main(String [] args) throws IOException{
URL url = new URL("my url which return JSON structure");
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
str += scan.nextLine();
scan.close();
JSONObject obj = new JSONObject(str);
JSONObject res = obj.getJSONArray("items").getJSONObject(0);
System.out.println(res.getInt("id"));
}
}
Eclipse
my errors:
Exception in thread "main" org.json.JSONException: JSONObject["items"] not found.
at org.json.JSONObject.get(JSONObject.java:472)
at org.json.JSONObject.getJSONArray(JSONObject.java:619)
at VK.main(VK.java:26)
You need to go one more level deep.
JSONObject obj = new JSONObject(str);
JSONObject firstItem = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0);
System.out.println(firstItem.getInt("id"));
try this:
JSONObject obj = new JSONObject(str);//assuming that obj is the same object as in the example
//to get the id
int id = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0).getInt("id");
In case that you are parsing Array of objects
JSONArray jsonArray = new JSONArray(stringToParse);
than continue as usual
Related
I am a newbie to java. I have a JSONArray like this
String data1 = "[{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-28T18:37:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-29T18:35:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-30T18:41:00.000Z\"},\"sort\":[1576653361739],\"_score\":null}]";
String data2 = "[ { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-28T18:37:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-29T18:35:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-17T18:35:00.000Z\" }, \"sort\": [ 1576653361736 ], \"_score\": null } ]" ;
JSONArray jsonElement1 = new JSONArray(data1) ;
JSONArray jsonElement2 = new JSONArray(data2) ;
After conversion:
jsonElement1 = [
{"_index":"sales_csv","_source":{"Order Date":"2016-01-28T18:37:00.000Z"},"sort":[1576653361740],"_score":null},
{"_index":"sales_csv","_source":{"Order Date":"2016-01-29T18:35:00.000Z"},"sort":[1576653361740],"_score":null},
{"_index":"sales_csv","_source":{"Order Date":"2016-01-30T18:41:00.000Z"},"sort":[1576653361739],"_score":null}]
jsonElement2 = [
{ "_index": "sales_csv", "_source": { "Order Date": "2016-01-28T18:37:00.000Z" }, "sort": [ 1576653361740 ], "_score": null },
{ "_index": "sales_csv", "_source": { "Order Date": "2016-01-17T18:35:00.000Z" }, "sort": [ 1576653361736 ], "_score": null },
{ "_index": "sales_csv", "_source": { "Order Date": "2016-01-29T18:35:00.000Z" }, "sort": [ 1576653361740 ], "_score": null }, ]
I need to compare both the JSONArray and return the common JSONobjects between both the array and append it to the new JSONarray output
Required Output:
output = [
{ "_index": "sales_csv", "_source": { "Order Date": "2016-01-28T18:37:00.000Z" }, "sort": [ 1576653361740 ], "_score": null },
{ "_index": "sales_csv", "_source": { "Order Date": "2016-01-29T18:35:00.000Z" }, "sort": [ 1576653361740 ], "_score": null }
]
I tried this answer Comparing 2 JSONArray. But it returns either true/ false.
Here's the Code I tried:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.util.*;
import static java.lang.System.out;
public class home {
public static JSONArray sortJsonArray(JSONArray inputUnSort, JSONArray outputSort) throws JsonProcessingException {
for (int i = 0; i < inputUnSort.length(); i++) {
ObjectMapper om = new ObjectMapper();
om.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
Map<String, Object> map = null;
try {
map = om.readValue(inputUnSort.getJSONObject(i).toString(), HashMap.class);
} catch (IOException e) {
e.printStackTrace();
}
String jsonstr = om.writeValueAsString(map);
JSONObject json = new JSONObject(jsonstr);
outputSort.put(json);
}
return outputSort;
}
public static JSONArray compareJsonArray(JSONArray jsonElement1, JSONArray jsonElement2) throws JsonProcessingException {
// Sorting
JSONArray jsonElement1sort = new JSONArray() ;
JSONArray jsonElement2sort = new JSONArray();
jsonElement1sort = sortJsonArray( jsonElement1, jsonElement1sort);
jsonElement2sort = sortJsonArray( jsonElement2, jsonElement2sort);
JSONArray outputJSONelement = new JSONArray();
for (int i = 0; i < jsonElement1sort.length(); i++){
for (int j = 0; j < jsonElement2sort.length(); j++) {
if (jsonElement1sort.getJSONObject(i).toString().equals(jsonElement2sort.getJSONObject(j).toString())){
outputJSONelement.put(jsonElement1sort.getJSONObject(i));
}
}
}
return outputJSONelement;
}
public static void main(String[] args) throws JsonProcessingException {
String data1 = "[{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-28T18:37:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-29T18:35:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-30T18:41:00.000Z\"},\"sort\":[1576653361739],\"_score\":null}]";
String data2 = "[ { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-28T18:37:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-29T18:35:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-17T18:35:00.000Z\" }, \"sort\": [ 1576653361736 ], \"_score\": null } ]" ;
JSONArray jsonElement1 = new JSONArray(data1) ;
JSONArray jsonElement2 = new JSONArray(data2) ;
out.println(jsonElement1);
out.println(jsonElement2);
out.println(compareJsonArray(jsonElement1, jsonElement2));
}
}
The above code looks huge.
Any shortest way to achieve this
Since you are doing O(N^2) comparison to find the common elements already, you don't need to sort the array before. Just removing the sorting should also work and reduce a good amount of redundant code
Instead of string comparison use JSONObject.similar()
This is the json I'm working with. I need to print description object which is inside weather array. I am getting JSONArray[2] not found exception while compiling. I'm using java-json.
{
"coord": {
"lon": 72.85,
"lat": 19.01
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50n"
}
],
"base": "stations",
"main": {
"temp": 303.15,
"pressure": 1009,
"humidity": 74,
"temp_min": 303.15,
"temp_max": 303.15
},
"visibility": 3000,
"wind": {
"speed": 2.1,
"deg": 360
},
"clouds": {
"all": 20
},
"dt": 1539273600,
"sys": {
"type": 1,
"id": 7761,
"message": 0.0642,
"country": "IN",
"sunrise": 1539219701,
"sunset": 1539262109
},
"id": 1275339,
"name": "Mumbai",
"cod": 200
}
this is the code--
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONArray;
class Send_HTTP_Request2 {
public static void main(String[] args) {
try {
Send_HTTP_Request2.call_me();
} catch (Exception e) {
e.printStackTrace();
}
}
static void call_me() throws Exception {
String url = "http://api.openweathermap.org/data/2.5/weather?id=1275339&APPID=77056fb4e0ba03b117487193c37c90d2";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject myResponse = new JSONObject(response.toString());
JSONArray jrr= myResponse.getJSONArray("weather");
System.out.println("CITY-"+myResponse.getString("name"));
JSONObject desc = jrr.getJSONObject(2);
System.out.println(desc);
}
}
For the JSONArray method of getJSONObject(int index) (Link to the Javadoc here)
You're right to grab the JSONObject inside of the array, but you're grabbing the wrong index, which in this case, is 0 since in Java, index 0 is the first item of the array. (More on Arrays and indexes here)
And then you would just call desc.getString("description") and assign it to a String, since the description key is a String type.
So more specifically you'd do something link this (assuming we're not checking for nulls or iterating through the array with a for loop or anything):
JSONObject myResponse = new JSONObject(response.toString());
JSONArray jrr= myResponse.getJSONArray("weather");
System.out.println("CITY-"+myResponse.getString("name"));
JSONObject weatherObj = jrr.getJSONObject(0);
String desc = weatherObj.getString("description");
System.out.println(desc);
Hope this helps!
Edited for formatting
I want to get "weather" data from JSONObject but this error is coming.
org.json.JSONException: JSONObject["weather"] not a string.
at org.json.JSONObject.getString(JSONObject.java:639)
at GetWeather.main(GetWeather.java:49)
This is my code
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GetWeather {
public static String getWeather(String args){
String result =" ";
URL url ;
HttpURLConnection urlConnection = null;
try{
url = new URL(args);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data= reader.read();
while(data!=-1){
char current=(char) data;
result += current;
data= reader.read();
}
return result;
}catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//main
public static void main(String[] args){
String s1 = getWeather(args[0]);
try {
JSONObject jsonObject = new JSONObject(s1);
String weather= jsonObject.getString("weather");
System.out.println(weather);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the string which I am passing
http://api.openweathermap.org/data/2.5/weather?q=Delhi&APPID=04b767167643ea6af521695e7948e0fb
This is the data I get back
{"coord":{"lon":77.22,"lat":28.67},"weather":[{"id":721,"main":"Haze","description":"haze","icon":"50d"}],"base":"stations","main":{"temp":305.86,"pressure":1007,"humidity":38,"temp_min":304.15,"temp_max":307.15},"visibility":3500,"wind":{"speed":1.5,"deg":320},"clouds":{"all":0},"dt":1508241600,"sys":{"type":1,"id":7808,"message":0.0051,"country":"IN","sunrise":1508201604,"sunset":1508242734},"id":1273294,"name":"Delhi","cod":200}
Which in formatted version looks like
{
"coord": {
"lon": 77.22,
"lat": 28.67
},
"weather": [{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50d"
}
],
"base": "stations",
"main": {
"temp": 305.86,
"pressure": 1007,
"humidity": 38,
"temp_min": 304.15,
"temp_max": 307.15
},
"visibility": 3500,
"wind": {
"speed": 1.5,
"deg": 320
},
"clouds": {
"all": 0
},
"dt": 1508241600,
"sys": {
"type": 1,
"id": 7808,
"message": 0.0051,
"country": "IN",
"sunrise": 1508201604,
"sunset": 1508242734
},
"id": 1273294,
"name": "Delhi",
"cod": 200
}
Please tell me whats wrong with my code and what to do.
The value of "weather" that you're trying to get is not a String, but a JSONArray.
In order to read all the information inside it, try using getJSONArray():
try {
JSONObject jsonObject = new JSONObject(s1);
// read the `weather` content
JSONArray weatherArray = jsonObject.getJSONArray("weather");
// get only the first element of `weather`, the only one existing
JSONObject weatherObject = (JSONObject)weatherArray.get(0);
// read all its' properties
for (Object key : weatherObject.keySet()) {
System.out.println("key:" + key + ", value: " + weatherObject.get((String)key));
}
} catch (JSONException e) {
e.printStackTrace();
}
For other info like "temp" or "pressure", just use getJSONObject() since "main" has JSONObject type:
JSONObject mainObject = jsonObject.getJSONObject("main");
System.out.println("pressure value: " + mainObject.get("pressure"));
System.out.println("temp value: " + mainObject.get("temp"));
How can I read this file using JsonObject and JsonArray? And how can I retrieve the typeId value?
{
"mockup": {
"controls": {
"control": [
{
"ID": "5",
"measuredH": "400",
"measuredW": "450",
"properties": {
"bold": "true",
"bottomheight": "0",
"italic": "true",
"size": "20",
"text": "Test",
"topheight": "26",
"underline": "true",
"verticalScrollbar": "true"
},
"typeID": "TitleWindow",
"x": "50",
"y": "50",
"zOrder": "0"
},
{
"ID": "6",
"measuredH": "27",
"measuredW": "75",
"properties": {
"align": "left",
"bold": "true",
"color": "0",
"italic": "true",
"menuIcon": "true",
"size": "18",
"state": "selected",
"text": "OK",
"underline": "true"
},
"typeID": "Button",
"x": "67",
"y": "85",
"zOrder": "1"
}
]
},
"measuredH": "450",
"measuredW": "500",
"mockupH": "400",
"mockupW": "450",
"version": "1.0"
}
}
I'm using this code:
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
private static final String _strDesktopDirectory = System.getProperty("user.home") + "/Desktop";
public static void main(String[] args) {
JSONParser _jspMyJsonParser = new JSONParser();
JFileChooser _fcMyFileChooser = new JFileChooser("Open JSON File");
FileNameExtensionFilter _fneJsonFilter = new FileNameExtensionFilter("JSON Files (*.json)", "json");
_fcMyFileChooser.setFileFilter(_fneJsonFilter);
int _iReturnFile = _fcMyFileChooser.showOpenDialog(_fcMyFileChooser);
_fcMyFileChooser.setCurrentDirectory(new File(_strDesktopDirectory));
if (_iReturnFile == JFileChooser.APPROVE_OPTION) {
try {
String _strSelectedFile = _fcMyFileChooser.getSelectedFile().toString();
Object _oMyObject = _jspMyJsonParser.parse(new FileReader(_strSelectedFile));
// Exception Here.
JSONObject _jsnoMockup = (JSONObject) _oMyObject;
_jsnoMockup = (JSONObject) _jsnoMockup.get("mockup");
JSONObject _jsnoControls = (JSONObject) _jsnoMockup.get("controls");
System.out.println("Mockup: " + _jsnoMockup);
System.out.println("Controls: " + _jsnoControls);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
} else {
System.out.println("Close");
System.exit(0);
}
}
}
The error is:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.JSONObject
Note: I don't have any experience with Java.
The method getJSONfromURL returns the JSON of the given URL and that works just fine but the error is in JSONArray jsonArray = (JSONArray)jsonobject;
It gives the following error: cannot cast JSONObject to JSONArray. I've also tried this: JSONArray jsonArray = (JSONObject)(JSONArray)jsonobject;
I can't figure out what I'm doing wrong.
try with below one
JSONArray jsonArray = new JSONArray();
jsonArray = jsonObject.getJSONObject("mockup").getJSONObject("controls").getJSONArray("control");
for(i=0;i<jsonArray.lenght();i++){
System.out.println(jsonArray.getJSONObject(i).getString("typeID"));
}
I have this json file I downloaded online:
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
and I want to delete everything from
"empty": [
to
],
I've spent a few hours looking at regex stuff and I can't seem to figure out how to make it do what I want it to do.
Edit:
Annamalai Thangaraj's method works until I add more to the file.
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
{
"price": 500,
"empty": [
5,
0,
3,
6,
9
],
"lowValue": 4,
"highValue": 2
}
which now I'm given an error:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.JsonArray cannot be cast to com.google.gson.JsonObject
My code is exactly:
public static void go() throws IOException {
JsonObject jsonObject = (JsonObject)JsonParser.parse(new FileReader(location));
jsonObject.remove("empty");
JsonArray jsonArray = (JsonArray)JsonParser.parse(new FileReader(location));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonObject.toString());
String prettyJsonString = gson.toJson(je);
FileWriter file = new FileWriter(System.getProperties().getProperty("user.home")+"\\output.json");
try {
file.write(prettyJsonString);
System.out.println("Successfully wrote JSON object to file.");
} catch (IOException e) {
e.printStackTrace();
} finally {
file.flush();
file.close();
}
}
Use the following code to remove element empty from json
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("File Path"));
jsonObject .remove("empty");
After removing empty element using jsonObject.toJSONString() to get target JSON, Now structure of JSON will be look like this
{
"price": 1,
"lowValue": 0,
"highValue": 0
},
Use a JSON library like Jackson:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
public class JsonDelete {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"key\":\"value\",\"empty\":[]}";
ObjectNode node = (ObjectNode) mapper.readTree(json);
node.remove("empty");
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node));
}
}
Outputs:
{
"key" : "value"
}
If you put a '[' at the beginning and a ']' at the end of json file, it becomes a valid json file. Like in your json file, It should be.
[
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
{
"price": 500,
"empty": [
5,
0,
3,
6,
9
],
"lowValue": 4,
"highValue": 2
}
]
So the final program will be like:--
public class ReadJSONFromFile {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("locationOfFIle"));
JSONArray array = (JSONArray) obj;
FileWriter file = new FileWriter("locationOfFIle");
for (int index = 0; index < array.size(); ++index) {
JSONObject jsonObject = (JSONObject) array.get(index);
jsonObject.remove("empty");
file.write(jsonObject.toJSONString());
file.flush();
if (index == array.size() - 1)
file.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can also parse your json by ignoring some fields. Look at this example:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
#JsonIgnoreProperties(value = { "empty" })
public class Item {
private long price;
private long lowValue;
private long highValue;
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public long getLowValue() {
return lowValue;
}
public void setLowValue(long lowValue) {
this.lowValue = lowValue;
}
public long getHighValue() {
return highValue;
}
public void setHighValue(long highValue) {
this.highValue = highValue;
}
#Override
public String toString() {
return "Item [price=" + price + ", lowValue=" + lowValue + ", highValue=" + highValue + "]";
}
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String file = "c:\\json";
ObjectMapper mapper = new ObjectMapper();
Item[] items = mapper.readValue(new File(file), Item[].class);
for (Item item : items) {
System.out.println(item);
}
}
}
c:\json contains:
[
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
{
"price": 2,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 3,
"highValue": 4
}
]
Output is:
Item [price=1, lowValue=0, highValue=0]
Item [price=2, lowValue=3, highValue=4]