I need to convert JSON string to Object[].
I tried with link1 and link2 and did not help me.
Code how i get JSON string:
public static String getListJsonString() {
String getListsUrl = BASE_URL + "lists";
String result = "";
try {
URL url = new URL(getListsUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + getAuthStringEnc());
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
result = sb.toString();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
This is example of my JSON:
And after i must fill ChomboBox on this way (this is example):
Object[] lists = getLists();
for(Object list : lists){
System.out.println("fill combobox");
}
You can use Gson, TypeToken and JSONObject, example:
final static Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
final Type objectType = new TypeToken<Object>(){}.getType();
JSONObject obj = new JSONObject(result);
Vector<Object> lists = gson.fromJson(obj.toString(), objectType);
I suggest you should be using jackson lib. I linked a great quick tutorial that I find really clear and useful.
The idea behind jackson lib is that JSON format is a stringified Object format so you should be able to map it properly to java POJOs easily. (POJO = Plain old java object, which is an object with some fields, maybe some annotations on top of your fields and finally just getters and setters).
You can auto generate Jackson annotated POJOs classes from a json string using this link : http://www.jsonschema2pojo.org/ (just select "JSON" instead of "JSON SCHEMA", and maybe tune the other parameters depending on your need).
I can feel your pain sometimes it's hard to get a quick example up and running.
This is a very simple example how you can read your json document using Jackson library. You need a minimum of jackson-annotations-x.y.z.jar, jackson-core-x.y.z.jar and jackson-databind-x.y.z.jar files in a classpath.
https://github.com/FasterXML/jackson-databind/
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
public class TestJSON1 {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonObj;
String jsonStr = "{ \"list\": [ "
+ " {\"id\":\"1\", \"name\":\"test1\"}, "
+ " {\"id\":\"2\", \"name\":\"test2\"}, "
+ " {\"id\":\"3\", \"name\":\"test3\"} "
+ "]}";
jsonObj = mapper.readTree(jsonStr);
System.out.println(jsonObj.get("list"));
JsonNode jsonArr=jsonObj.get("list");
int count=jsonArr.size();
for (int idx=0; idx<count; idx++) {
jsonObj = jsonArr.get(idx);
System.out.println( jsonObj.get("id").asText()+"="+jsonObj.get("name").asText() );
}
}
}
Related
I created a post request with json and it works pretty well. But now I want to insert the output of this json post request into my database.
So I need to create a json parser to seperate the string like this: "Bestellnummer:1", "Besteller:8195529", "Zeit: 2019-09-27 15:50:07", "Artikelnummer:76194", "Anzahl:1", "Preis:2.968"... (next Artikelnummer and so on...).
Bestellnummer = orderid, Besteller = customerid, Zeit = time, Artikelnummer=articleid, Anzahl = number of article, Preis= price
I tried to do something like a parser in my code, but I never did something like this befor and unfortuntly don't know how to involve this parser in my code.
I hope u can help me
One example for my json Output:
{"Bestellnummer":"1","Besteller":"8195529","Zeit":"2019-09-27 15:50:07","Artikel":[{"Artikelnummer":"76194","Anzahl":"1","Preis":"2.968"},{"Artikelnummer":"61681","Anzahl":"1","Preis":"7.147"},{"Artikelnummer":"111756","Anzahl":"1","Preis":"9.29"},{"Artikelnummer":"14227","Anzahl":"1","Preis":"0"}]}
Code:
private static String dirPath = "https://hauteuchdrum.informatik.uni-siegen.de/propra/aufgaben/ws1920/index.php";
public ArrayList<String> Bestellung(){
File file = new File (dirPath + "//array_complex.json");
ArrayList <String> test = new ArrayList<String>();
try {
String str = "{ \"Bestellnummer\": [1,2,3,4,5] }";
// holt alle 47550 bestellungen vom json
for (int i=1; i<2;i++) {
String POST_PARAMS = "json={\"bid\":\"bid\", \"getorder\":\""+i+"\"}";
//System.out.println(POST_PARAMS);
JSONObject obj1 = new JSONObject(POST_PARAMS);
JSONArray arr=obj1.getJSONArray("Bestellnummer");
for (int z=0; z<arr.length();z++) {
String post_id = arr.getJSONObject(z).getString("Bestellnummer");
System.out.println(post_id);
}
URL obj = new URL("https://hauteuchdrum.informatik.uni-siegen.de/propra/aufgaben/ws1920/index.php");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("connection", "Keep-Alive");
postConnection.setDoOutput(true);
java.io.OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
//System.out.println("POST Response Code : " + responseCode);
// System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
// System.out.println(response.toString());
test.add(response.toString());
// java.util.Iterator<String> it = test.iterator();
// while (it.hasNext()) {
// System.out.println(it.next());
// }
}
}
}
catch (Exception e) {
System.out.println();
}
return test;
}
If what you want to do is to insert the HTTP response string into database, I strongly recommend you to deserialize the string to POJOs as follows:
Declare 2 classes - MyResponse and Artikel. Artikel is for storing the content of JOSN object in JSON array, and I use List<Artikel> for the JSON array. BTW, I also use #JsonProperty(provided in Jackson) to map JSON keys with uppercase to variables with lowercase.
class MyResponse {
#JsonProperty(value="Bestellnummer")
private String bestellnummer;
#JsonProperty(value="Besteller")
private String besteller;
#JsonProperty(value="Zeit")
private String zeit;
#JsonProperty(value="Artikel")
private List<Artikel> artikel;
//general getters and setters
}
class Artikel {
#JsonProperty(value="Artikelnummer")
private String artikelnummer;
#JsonProperty(value="Anzahl")
private String anzahl;
#JsonProperty(value="Preis")
private String preis;
//general getters and setters
}
Now, you can use Jackson (one of the most popular JSON libraries) to deserialize the HTTP response to our POJOs. And you can manipulate these POJOs for DB operation easily.
ObjectMapper mapper = new ObjectMapper();
MyResponse myResponse = mapper.readValue(response.toString(), MyResponse.class);
myResponse.getArtikel().forEach(System.out::println);
Console output
Artikel [artikelnummer=76194, anzahl=1, preis=2.968]
Artikel [artikelnummer=61681, anzahl=1, preis=7.147]
Artikel [artikelnummer=111756, anzahl=1, preis=9.29]
Artikel [artikelnummer=14227, anzahl=1, preis=0]
Because you provided too less information to come up with a more detailed answer I came up with the following code.
JSONObject main = new JSONObject(data);
String orderNumber = main.getString("Bestellnummer"); // Retrieving the order number
String orderUserId = main.getString("Besteller"); // Retrieving the orderUserId
String time = main.getString("Zeit"); // Retrieving the current time
JSONArray articles = main.getJSONArray("Artikel"); // Getting articles as JSON Array
for (int i = 0; i < articles.length(); i++) { // Looping tough the articles
JSONObject article = articles.getJSONObject(i); // Getting the article JSON Object
String articleNumber = article.getString("Artikelnummer"); // Retrieving the Article number
String amount = article.getString("Anzahl"); // Retrieving the amount
String price = article.getString("Pris"); // Retrieving the price
// Your code...
}
I hope this helps you.
I am getting a json from rest call as {"d1":1, "d2":1, "d3":0, "d4":1} which is stored in db as - {d1=1, d2=1, d3=0, d4=1}.
When I am reading from database i am getting the above as string as - {d1=1, d2=1, d3=0, d4=1}. I want to convert this to its original form as before like - {"d1":1, "d2":1, "d3":0, "d4":1} mentioned above.
How can i achieve this in java. is there any json library available to do this ?
Sofar I have tried this but it didn't worked out -
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsonString);
I want to put this json in ResponseEntity>.
Even I tried -
jsonString = jsonString.replaceAll("=", ":");
JSONObject jsonObject = new JSONObject(jsonString);
String finalJsonString = jsonObject.toString();
This is giving back response as "{\"d1\":1, \"d2\":1, \"d3\":0, \"d4\":1}" with double quotes in the begining and ending with backslashes before double quotes for keys.
The String returned through DB is not in JSON format, so parsing fails.
You could use the following approach to format the returned string into a JSON string, and then parse it.
I have used Guava's Splitter.MapSplitter:
String in = "{d1=1,d2=1,d3=0,d4=1}";
in = in.replaceAll("[{}]", "");
Map<String, String> properties = Splitter.on(",").withKeyValueSeparator("=").split(in);
JSONObject obj = new JSONObject(properties);
String formattedString = obj.toString();
The string that you are retrieving from DB is a Map data structure. So you can convert a Map to JSON as follows:
Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");
String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);
Edited
The following code snippet will provide you the complete JSON response.
#RestController
#RequestMapping("/api/v1/")
public class TestController {
#GetMapping(value="test",produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> test() {
Map<String,String> payload = new HashMap<>();
payload.put("d1","value1");
payload.put("d2","value2");
payload.put("d3","value3");
payload.put("d4","value4");
String json =null;
try {
json= new ObjectMapper().writeValueAsString(payload);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return new ResponseEntity(json,HttpStatus.OK);
}
}
Postman test:
You can do as follows :
ObjectMapper mapper = new ObjectMapper();
try {
MyResponse result = mapper.readValue(e.getResponseBodyAsString(),MyResponse.class);
return result;
} catch (IOException e1) {
e1.printStackTrace();
}
I have a trouble finding a way how to parse JSONArray.
It looks like this:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects).
But it's all I have and have to go with it.
*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.
There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.
Can somebody please give me some hint, or a tutorial or an example?
Much appreciated !
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
#JsonProperty("name")
public String mName;
#JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
In this example there are several objects inside one json array. That is,
This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
This is one object: {"name":"name1","url":"url1"}
Assuming that you have got the result to a String variable called jSonResultString:
JSONArray arr = new JSONArray(jSonResultString);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("url");
}
public class CustomerInfo
{
#SerializedName("customerid")
public String customerid;
#SerializedName("picture")
public String picture;
#SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
A few great suggestions are already mentioned.
Using GSON is really handy indeed, and to make life even easier you can try this website
It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project.
You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
My case
Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);
So far with the code I have, I am able to get results as a JsonObject. However, I am trying to get the coordinates of the location based on the postal code that I have entered. How can I retrieve the "lat" and "lng" as Strings/JsonElements? Would really appreciate if you can give me some insight. Thanks!
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
//the JSON builder
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String restaurant = request.getParameter("r");
String customer = request.getParameter("c");
//Get coordinates of the restaurant
String longLatApi = "https://maps.googleapis.com/maps/api/geocode/json?address=" + restaurant;
URL url = new URL(longLatApi);
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", longLatApi);
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
String jsonString = builder.toString();
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
out.println(gson.toJson(obj));
JsonElement and its subclasses have nice methods to iterate through JSON elements of different kinds: null, a primitive (numbers, string literals, and booleans), a JSON object, or a JSON array. Knowing an exact structure of the response JSON document, you can extract child elements pretty straight-forward:
final URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=Greenwich");
// Let Gson parse the JSON input stream without expensive intermediate strings
try ( final Reader reader = new BufferedReader(new InputStreamReader(url.openStream())) ) {
final JsonParser jsonParser = new JsonParser();
// Extract the `results` array
final JsonArray resultsJsonArray = jsonParser.parse(reader)
.getAsJsonObject()
.get("results")
.getAsJsonArray();
// Iterate over each result array element
for ( int i = 0; i < resultsJsonArray.size(); i++ ) {
final JsonObject resultJsonObject = resultsJsonArray.get(i).getAsJsonObject();
System.out.println(resultJsonObject.getAsJsonPrimitive("formatted_address").getAsString());
// Picking up the `geometry` property as a JSON object
final JsonObject geometryJsonObject = resultJsonObject.get("geometry").getAsJsonObject();
// And dumping the location
final JsonObject locationJsonObject = geometryJsonObject.get("location").getAsJsonObject();
dumpLocationJsonObject("Location", locationJsonObject);
final JsonElement boundsJsonElement = geometryJsonObject.get("bounds");
// There can be a `bounds` object with two additional properties
if ( boundsJsonElement != null && !boundsJsonElement.isJsonNull() ) {
final JsonObject boundsJsonObject = boundsJsonElement.getAsJsonObject();
dumpLocationJsonObject("North/East", boundsJsonObject.get("northeast").getAsJsonObject());
dumpLocationJsonObject("South/West", boundsJsonObject.get("southwest").getAsJsonObject());
}
}
}
private static void dumpLocationJsonObject(final String name, final JsonObject location) {
final double latitude = location.getAsJsonPrimitive("lat").getAsDouble();
final double longitude = location.getAsJsonPrimitive("lng").getAsDouble();
System.out.println("\t" + name + ": (" + latitude + "; " + longitude + ")");
}
The output:
Greenwich, London SE10, UK
Location: (51.48257659999999; -0.0076589)
As an alternative approach, you can define custom JSON to Java classes mappings in order to deserialize the JSON document as a custom class instance, and not just JsonElement (something like gson.fromJson(reader, customType)). Both approaches have pros and cons.
I did a http client and I'm getting a response. I am using a JSONObject to parse the data and when I execute the code below it prints out all of the JSON just fine
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(entity!=null){
try(InputStream instream = entity.getContent()) {
String responseString = readInputStream(instream);
JSONObject job = new JSONObject(responseString);
statusLabel.setText("Command Result: " + job.toString());
Here is the readInputSream function:
static private String readInputStream(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "UTF-8"));
String tmp;
StringBuilder sb = new StringBuilder();
while ((tmp = reader.readLine()) != null) {
sb.append(tmp).append("\n");
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
sb.setLength(sb.length() - 1);
}
reader.close();
return sb.toString();
}
If I change it from job.toString() to:
statusLabel.setText("Command Result: " + job.get("result"));
it prints a 1 which is correct, it works all the way up to my_list. I'm not sure how to parse the list. I put a snippet of the response below. Ive tried "my_list", "my_list[]", my_list[0]" which none have worked. I get JSONObject "blank" not found
{"result":1, "ver":1,"total":2,"catch":true,"my_list":[{"id":3,"mid":0,"format":3,"user":4,"property":1,"type":0,"title":"hello","start":146,"end":1464,"hid":3,"bid":1,"reason":1,"time":0,"creator":"1","hello":0,"my":0,"year":"0","ggg":614,"name":"","ch":"0","attr":0,"type":1,"vtype":1,"tm_log": {"fr":4,"action":0,"vr":"82","started":1,"av_ended":2,"tr":1}}
The element you trying to retrieve is parsed into a JSONArray, not a JSONObject. Try:
JSONArray my_list = job.getJSONArray("my_list");
Assuming that you are using json parser project JSON-java to parse your JSON you need to retrieve a JSONArray instance - this is how arrays are storred in JSONObject. so do the following: JSONArray my_list = job.getJSONArray("my_list"); and then use methods of JSONArray class to access your array. The Javadoc to JSON-java package can be found here: http://stleary.github.io/JSON-java/index.html. Also note that JSON-java is very simple and easy to use JSON parser project but it is not very efficient for any serious project. Common recommendation for commercial use is Jackson JSON Processor which is one of the fastest and powerful JSON parsers. Here are some links to read about it: https://github.com/FasterXML/jackson, http://wiki.fasterxml.com/JacksonHome