I have read the posts that appeared to be the same as my question but I must be missing something. My environment is Eclipse Mars. My JAVA is 1.7 and I have imported json-simple. I simply wish to parse the json that is returned from my web service. I control the web service if I need to modify its output. I see the json in arg[0] as noted below however the Object obj is null as of course is the JSONArray array. I know that I am missing something basic but I am stumped and a bit tired.
Here is the returned json:
[{"$id":"1","NumberID":121183,"PortfolioID":718,"PropertyID":14489,"Adsource":17287,"PlanTypeID":1,"GreetingFile":"HolidayGreeting.wav","PromptFile1":"senior.leasing.first.wav","Accepts1":2,"PromptAction_ID1":1,"PromptFile2":"Default.wav","Accepts2":2,"PromptAction_ID2":1,"PromptFile3":"Default.wav","Accepts3":2,"PromptAction_ID3":1,"PromptFile4":"Default.wav","Accepts4":2,"PromptAction_ID4":1,"PromptFile5":"Default.wav","Accepts5":2,"PromptAction_ID5":1,"HoldMsgFile1":"SpectrumHold.wav","HoldMsgFile2":"Default.wav","Destination1":15197,"Destination2":15024,"Destination3":0,"UIType_ID":16,"RingCount":0,"Enabled":true,"Spanish":false,"HoldMusicFile":"Hold_Music.wav","Template_ID":41,"FrontLineForward":true,"DisclaimerFIle":"1Silence.wav"}]
Here is the parse code employing json-simple:
package parser;
import org.json.simple.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
public class JsonParser
{
private static JSONObject _jsonInput;
public static void main(String[] args)
{
//TODO
try{
JSONParser parser = new JSONParser();
Object obj = JSONValue.parse(args[0]);
JSONArray array=(JSONArray)obj;
String name = array.get(3).toString();
System.out.println(obj);
}
catch(Exception e){
e.printStackTrace();
}
}
}
The size of the array different than the index used
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(args[1]));
JSONArray array=(JSONArray)obj;
if (array.size() > 3)
String name = array.get(3).toString();
Related
using gson, I parsed data in json format and now I need to extract the value "dt_txt" and their value "temp" from this data and I don’t understand how to pull and paste them into the collection where the key is "dt_txt" and its value is "temp "
The data that I received: https://imgur.com/a/qAxwEri
package testClassPackage;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class weatherParse {
public static void main(String[] args) throws IOException {
String sURL = "http://api.openweathermap.org/data/2.5/forecast/?q=Odessa,ua&APPID=518a64dd48106aa542464d3bd94d12ce"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
JsonArray message = rootobj.get("list").getAsJsonArray();
for (int i = 0; i < message.size(); i++) {
System.out.println();
}
System.out.println(message);
}
}
iterate over the JsonArray(message I changed to messages here) as JsonElement and get main object from the element then fetch th corresponding temp.
Map<String,String> data = new HashMap<>();
for(JsonElement lst : messages) {
JsonObject lstObject = lst.getAsJsonObject();
JsonObject el = (JsonObject) lstObject.get("main");
System.out.println(lstObject.get("dt_txt").getAsString() +" "+el.get("temp").getAsString());
data.put(lstObject.get("dt_txt").getAsString(), el.get("temp").getAsString());
}
I have JSONObject[] in stringified format. I need to convert it back to JSONObject[] in java how I can achive that??
Sample Code :
JSONObject[] json = new JSONObject[10];
String jsonStrArray = "[{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3}]";
JsonParser parser = new JsonParser();
JsonObject jo = (JsonObject)
parser.parse(strFinalRecord).getAsJsonObject();
json = jo;
Error:
incompatible type
Required : org.json.JsonObject[]
Found : com.google.gson.JsonObject
If it is getting gson.JsonObject how to can I cast it to JsonObject[] ?
Please help me to resolve this issue
The json String you have created is not formatted correctly.
Try the following code.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonTest {
public static void main(String arg[]) throws ParseException {
JSONObject json = new JSONObject();
String jsonStrArray = "[{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"},{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"},{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}]";
JSONParser parser = new JSONParser();
JSONArray jo = (JSONArray) parser.parse(jsonStrArray);
System.out.println(jo);
json.put("key", jo);
System.out.println(json);
}
}
Use JSON-Simple
below is my code where Im trying to check id id =101 and getting the name= Pushkar assosiated with the id=101.But the code is not working as expected.
import org.json.simple.JSONArray;
import org.json.JSONException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class A6 {
public static void main(String[] args) throws ParseException, JSONException{
String out1="{\"Employee\":[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}";
//System.out.println(out1);
JSONParser parser=new JSONParser();
JSONObject obj=(JSONObject)parser.parse(out1);
//System.out.print(obj);
JSONArray jarr=(JSONArray)obj.get("Employee");
//System.out.print(jarr);
for (int i=0;i<jarr.size();i++)
{
JSONObject jobj=(JSONObject)jarr.get(i);
String ID1=(String)jobj.get("id");
System.out.println(ID1);
if(ID1!=null && out1.equals(ID1))
{
System.out.println("NAME"+jobj.get("name"));
}
}
}}
why do you compare out1 with ID1? Either you want to check if out1 contains ID1 (which is not very meaningfull, as you retrieve ID1 from out1) or you want to verify that ID1 equals 101. In that case you would rather want to say something like:
if(ID1!=null && "101".equals(ID1))
{
System.out.println("NAME"+jobj.get("name"));
}
Try to change if condition like this:
if(ID1!=null && out1.contains(ID1))
{
System.out.println("NAME"+jobj.get("name"));
}
Thanks.
I have this code and I tried to getting items from this JSON string but it failed.
I'm parsing the Json string from remote host.
package selectDB;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.*;
public class selectDB
{
public static void main(String[] args) throws IOException, ParseException
{
String s = "";
URL u = new URL("http://192.168.3.1/android/select.php");
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
for(String line; (line = reader.readLine()) != null;)
{
s+=line;
}
System.out.println(s);
}
}
the result is
{"result" : "true" , "messages" : [{"id":"866343023633578","latitute":"27","longitude":"31","number_phone":"01113171374"},{"id":"352168066354050","latitute":"27","longitude":"31","number_phone":"202222"},{"id":"50","latitute":"50","longitude":"100","number_phone":"50"},{"id":"110","latitute":"50","longitude":"50","number_phone":"110"},{"id":"120","latitute":"27","longitude":"31","number_phone":"120"},{"id":"130","latitute":"28","longitude":"29","number_phone":"120"},{"id":"140","latitute":"30","longitude":"40","number_phone":"140"},{"id":"800","latitute":"60","longitude":"30","number_phone":"800"},{"id":"353629054230064","latitute":"70","longitude":"80","number_phone":"120"}]}
Please help!
U can use the JsonReader class.
try (JsonReader in = Json.createReader(r)) {
JsonObject jsonObject= in.readObject();
YourObject obj = new YourObject();
obj.setSomething(jsonObject.getString("something", null));
// "something" is the key in the json file, null is the default
// when "something" was not found
} catch (JsonException | ClassCastException ex) {
throw new BadRequestException("Invalid Json Input");
}
you can use the Google Library GSON as well, it is easy to use and self explaining.
https://code.google.com/p/google-gson/
Gson Goals
Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
Allow pre-existing unmodifiable objects to be converted to and from JSON
Extensive support of Java Generics
Allow custom representations for objects
Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
I'm following this tutuorial here, and my JSON object is near enough the same, except I have this sort of format:
{"user":{
"SomeKeys":"SomeValues",
"SomeList":["val1","val2"]
}
}
Here is my relevant code:
Object obj = parser.parse(new FileReader("exampleJson.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject user = (JSONObject) jsonObject.get("user");
JSONArray list = (JSONArray) user.get("SomeList");
Then my program goes off an gets the values form the keys etc. Or it would but I get a NullPointerException from eclipse. Why is this?
It should unpackage my .json file into jsonObject, unpackage the "user" key as a JSONObject user, then unpackage the "SomeList" key as a JSONArray called list. Except when it does so it must be trying to put one of val1 or val2 into a part of the JSONArray that does not exist and just points into the abyss of null. What have I done to deserve this wrong ?
How do I fix my program?
Your code is working well for me
public class App {
public static void main(final String[] args) throws FileNotFoundException, IOException, ParseException {
final Object obj = new JSONParser().parse(new FileReader("D:/a.json"));
final JSONObject jsonObject = (JSONObject) obj;
final JSONObject user = (JSONObject) jsonObject.get("user");
final JSONArray list = (JSONArray) user.get("SomeList");
System.out.println(list);
}
}
File D:/exampleJson.json
{"user":{
"SomeKeys":"SomeValues",
"SomeList":["val1","val2"]
}
}
output is
["val1","val2"]
Using the exact same json file:
{"user":{
"SomeKeys":"SomeValues",
"SomeList":["val1","val2"]
}
}
Here is the code I use (with the imports to really make sure we have the same ones):
import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Test {
public static void main(String[] args) throws Exception {
Object obj = new JSONParser().parse(new FileReader("t.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject user = (JSONObject) jsonObject.get("user");
JSONArray list = (JSONArray) user.get("SomeList");
System.out.println(list);
}
}
And here is the output:
["val1","val2"]
I used maven and m2e to import the library. The version used for this test was json-simple-1.1.jar.