Unable to Convert String into JSON using Java - java

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();
}

Related

How to implement a json parser here?

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.

JSON string to Object[]

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() );
}
}
}

Simple JSON unexpected token { at position > 1

I'm trying to use JSON simple as part of a Java application to pull specific data from a .json file. Whenever I run the program, I get an unexpected token error message when it tries to parse.
A simplified version of the JSON file is as follows:
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"}
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
My code is as follows:
public static void readJSON() {
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader(fileLocation);
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) jsonObject.get("");
Iterator<?> i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
int tweetID = (int) obj.get("id");
String lang = (String) obj.get("lang");
}
} catch (Exception e) {
e.printStackTrace();
}
}
In this example, the line of code:
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
throws an error due to an unexpected token at the first left brace ({) of the second JSON object (i.e, at the brace before "id":345).
How could I go about resolving this issue?
And, as a follow up, how would one also pull the information for the username in this example?
Thanks for taking the time to read through this, and for any assistance provided!
That file is an invalid JSON file, it contains an entire object on each line.
What you'll need to do is read the file line by line, and then passing each line to the parser to create a new object.
If you fix your code, you can solve unexpected token error.
public static void readJSON() {
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader(fileLocation);
//You need to fix this part
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
Iterator<?> i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
int tweetID = (int) obj.get("id");
String lang = (String) obj.get("lang");
}
} catch (Exception e) {
e.printStackTrace();
}
}
You are trying to parse JSON object, and you actually have two JSON objects.
And in your code you are actually expect an array of JSON objects.
So, use the proper JSON array:
[
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"},
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
]
In order to quickly check your JSON syntax, you can use some online tool.
Your JSON is indeed wrong. It actually contains 2 valid JSONs. If you want to create one valid JSON document you have to wrap your input with { and } or [ ] if this is an array or collection. Please note the comma that separates 2 different entities.
[
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"},
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
]

Read JSON in java servlet

I want to read this json in a servlet
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
Now i want to get this values to separately to string,jsonarray and json object
this is how i do that
PrintWriter out = response.getWriter();
try {
String newObj = request.getParameter("text");;
JSONObject jObj = new JSONObject(request.getParameter("obj"));
JSONArray jArray=new JSONArray(request.getParameter("all"));
out.print(newObj);
} catch (Exception e) {
e.printStackTrace();
out.write(e.toString());
}
response.setContentType("application/json");
your code is partially correct.String newObj = request.getParameter("jsondata"); is correct. Then you have to create the jObj from newObj string.
String jsonString = <your json String>
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject allObj = jsonObj.getJSONObject("obj");
JSONArray allArray = jsonObj.getJSONArray("all");
First read the data from request object :-
String jsonStr = request.getParameter("jsondata");
Use org.json library to parse it and create JsonObject :-
JSONObject jsonObj = new JSONObject(jsonStr );
Now, use this object to get your values :-
String id = jsonObj.getString("text");
You can see complete example here :-
How to parse Json in java
if your String data like ,
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
and It can get like,
String jsonData = request.getParameter("jsondata");
Parse to JSONObject is.
JSONObject jsonObject = new JSONObject(jsonData); // put "String"
You can get JSONArray like,
JSONArray jsonArray = jsonObject.getJSONArray("all");
good luck

how to achieve string conversion of list of maps in java

How can i convert JSON string to format given below and back to JSON string.
List<Map<String, String>> variables =new ArrayList<>();
I tried searching for this. Only thing which i could find is converting list to array and then to string. But using
TypeA[] array = a.toArray(new TypeA[a.size()]);
does not seems feasible here.
Converting List<Map<String,String>> to JSON string :
public String listmap_to_json_string(List<Map<String, String>> list)
{
JSONArray json_arr=new JSONArray();
for (Map<String, String> map : list) {
JSONObject json_obj=new JSONObject();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
try {
json_obj.put(key,value);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
json_arr.put(json_obj);
}
return json_arr.toString();
}
Or simply using google gson library:
public String listmap_to_json_string(List<Map<String, String>> list){
// Use toJson method to serialize list to Json
return new GsonBuilder().setPrettyPrinting().create().toJson(list);
}
Converting JSON string to List<Map<String,String>>:
public List<Map<String, String>> json_string_to_listmap(String json){
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Map<String, String>>>() {}.getType();
// Use fromJson method to deserialize json into an ArrayList of Map
return gson.fromJson(json , type);
}
For more informations check this link.
Indeed you should update your question to give more details. Meanwhile, with the current understanding I have from your post I would suggest you to look at ObjectMapper class from org.codehaus.jackson.map.
You will easily get a JSON converted in the type you want by using
// string in json format
String json;
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, TypeA.class);
This code show how convert json string to type List<Map<String,String>>:
ObjectMapper objectMapper = new ObjectMapper();
try {
TypeReference < List < Map < String, String >>> typeReference = new TypeReference < List < Map < String, String >>> () {
};
List < Map < String, String >> res = objectMapper.readValue("[{\"size\":\"100x200\"}]", typeReference);
System.out.println("type: " + typeReference.getType());
for (Map < String, String > map: res) {
for (String key: map.keySet()) {
System.out.println(key + " : " + map.get(key));
}
}
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources