I have a servlet in Java and I would like to know how I can do the following.
I have a String variable with the value of a name and want to create a Json with the variable being something like {"name": "David"}.
How do I do this?
I have the following code but I get an error :
Serious: Servlet.service () for servlet threw
exception servlet.UsuarioServlet java.lang.NullPointerException
at servlet.UsuarioServlet.doPost (UsuarioServlet.java: 166):
at line
String myString = new JSONObject().put("name", "Hello, World!").toString();
Your exact problem is described by Chandra.
And you may use the JSONObject using his suggestion.
As you now see, its designers hadn't in mind the properties, like chaining, which made the success of other languages or libs.
I'd suggest you use the very good Google Gson one. It makes both decoding and encoding very easy :
The idea is that you may define your class for example as :
public class MyClass {
public String name = "Hello, World!";
}
private Gson gson = new GsonBuilder().create();
PrintWriter writer = httpServletResponse.getWriter();
writer.write( gson.toJson(yourObject));
The json library based on Map. So, put basically returns the previous value associated with this key, which is null, so null pointer exception.( http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html#put%28java.lang.Object,%20java.lang.Object%29)
You can rewrite the code as follows to resolve the issue.
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name", "Hello, World");
String myString = jsonObject1.toString();
I tried with GSON, GSON is directly convert your JSONString to java class object.
Example:
String jsonString = {"phoneNumber": "8888888888"}
create a new class:
class Phone {
#SerializedName("phoneNumber")
private String phoneNumebr;
public void setPhoneNumber(String phoneNumebr) {
this.phoneNumebr = phoneNumebr;
}
public String getPhoneNumebr(){
return phoneNumber;
}
}
// in java
Gson gson = new Gson();
Phone phone = gson.fromJson(jsonString, Phone.class);
System.out.println(" Phone number is "+phone.getPhoneNumebr());
Related
Im trying to get a key:value pair from a simple jsonString to add it after into a memory tab. If facing an issue cause my input is a string. and it looks like my loop isnot able to read the key value pair.
I read many topics about it, and im still in trouble with it. As you can see below
{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}
and my method, find only on object... the result is the same in my loop
public static ArrayHandler jsonSimpleObjectToTab(String data) throws ParseException {
if( data instanceof String) {
final var jsonParser = new JSONParser();
final var object = jsonParser.parse(data);
final var array = new JSONArray();
array.put(object);
final var handler = new ArrayHandler("BW_funct_Struct");
for( KeyValuePair element : array) {
handler.addCell(element);
Log.warn(handler);
}
return handler;
} else {
throw new IllegalArgumentException("jsonSimpleObjectToTab: do not support complex object" + data + "to Tab");
}
}
i also tryed before to type my array as a List, Object etc, without the keyValuePair object, i would appreciate some help.
Thanks again dear StackOverFlowers ;)
You can try this :
const json = '{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}';
map = new Map();
const obj = JSON.parse(json,(key,value) => {
map.set(key,value)
});
and you'll have every pair stored in map
Simply split the whole line at the commas and then split the resulting parts at the colon. This should give you the individual parts for your names and values.
Try:
supposing
String input = "\"nom\":\"BRUN\",\"prenom\":\"Albert\"";
then
String[] nameValuePairs = input.split(",");
for(String pair : nameValuePairs)
{
String[] nameValue = pair.split(":");
String name = nameValue[0]; // use it as you need it ...
String value = nameValue[1]; // use it as you need it ...
}
You can use TypeReference to convert to Map<String,String> so that you have key value pair.
String json = "{\"nom\":\"BRUN\",\"prenom\":\"Albert\",\"date_naiss\":\"10-10-1960\",\"adr_email\":\"abrun#gmail.com\",\"titre\":\"Mr\",\"sexe\":\"F\"}";
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<Map<String,String>> typeReference = new TypeReference<Map<String, String>>() {
};
Map<String,String> map = objectMapper.readValue(json, typeReference);
I just answered a very similar question. The gist of it is that you need to parse your Json String into some Object. In your case you can parse it to Map. Here is the link to the question with my answer. But here is a short version: you can use any Json library but the recommended ones would be Jackson Json (also known as faster XML) or Gson(by Google) Here is their user guide site. To parse your Json text to a class instance you can use ObjectMapper class which is part of Jackson-Json library. For example
public <T> T readValue(String content,
TypeReference valueTypeRef)
throws IOException,
JsonParseException,
JsonMappingException
See Javadoc. But also I may suggest a very simple JsonUtils class which is a thin wrapper over ObjectMapper class. Your code could be as simple as this:
Map<String, Object> map;
try {
map = JsonUtils.readObjectFromJsonString(input , Map.class);
} catch(IOException ioe) {
....
}
Here is a Javadoc for JsonUtils class. This class is a part of MgntUtils open source library written and maintained by me. You can get it as Maven artifacts or from the Github
I am trying to validate this string below. Actually I am receiving this string in my servlet, now I need to validate these values at backend. What is the right way to do so. Shall I first convert it to JSON Object then to HashMap? Please suggest the correct/appropriate approach to be used here. I am quite new to Java and JSON.
String is
"{"if_ack":4},{"if_cmd":1,"if_state":1},{"if_cmd":1,"if_state":5}"
I am using GSON for processing JSON at server. For example:
InputStream is (send by client, JSON format)
Reader reader = new InputStreamReader(is);
Gson gson = new Gson();
List<YourClass> items = gson.fromJson(reader, new TypeToken<List<YourClass>>()
YourClass should have attributes like if_ack, if_state, if_cmd,...
Then you use as simple as this:
for (YourClass item : items) {
//do whatever you want
}
EDIT: your string should be in correct JSON format like this (JSON array): [{"if_ack":4}, {"if_cmd":1,"if_state":1}, {"if_cmd":1,"if_state":5}]
EXAMPLE:
You have JSON like this : [{"id": "1", "image": "test1"}, {"id": "2", "image": "test2"}]
YourClass.java should be:
public class YourClass{
private int id;
private String image;
//+ constructor, getters, setters,...
}
On server you can receive JSON from client side by InputStream is:
Reader reader = new InputStreamReader(is, "UTF-8");
Gson gson = new Gson();
List<YourClass> items = gson.fromJson(reader, new TypeToken<List<YourClass>>();
and then:
for (YourClass item: items){
//acces to item properties like item.id, item.image
}
I am using a httprequest to get Json from a web into a string.
It is probably quite simple, but I cannot seem to convert this string to a javax.json.JsonObject.
How can I do this?
JsonReader jsonReader = Json.createReader(new StringReader("{}"));
JsonObject object = jsonReader.readObject();
jsonReader.close();
See docs and examples.
Since the above reviewer didn't like my edits, here is something you can copy and paste into your own code:
private static JsonObject jsonFromString(String jsonObjectStr) {
JsonReader jsonReader = Json.createReader(new StringReader(jsonObjectStr));
JsonObject object = jsonReader.readObject();
jsonReader.close();
return object;
}
I know this is an outdated question and that this answer would not be relevant years back, but still.
Using Jackson Library is the easiest technique to solve this problem.
Jackson library is an efficient and widely used Java library to map Java objects to JSON and vice-versa. The following statement converts JSON String representing a student into a Java class representing the student.
Student student = new ObjectMapper().readValue(jsonString, Student.class);
Using Jackson to parse a string representation of a json object into a JsonNode object.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class J {
public static void main(String[] args) throws JsonProcessingException {
var json =
"""
{
"candle": {
"heat": 10,
"color": "orange"
},
"water": {
"heat": 1,
"color": null
}
}
""";
ObjectMapper mapper = new ObjectMapper();
var node = mapper.readTree(json);
System.out.println(node.toPrettyString());
}
}
I am new to Java and Android so please bear with me. I am trying to create a function which calls a wcf service and converts the returned result from JSON to a Java object (I pass the type as the object t), but it's throwing a null pointer exception on t, which must be null as I just want to pass an object of the correct type so that it becomes filled when converted. Kindly help me with it.
public static String Post(String serviceURL, Map<String, String> entites,
Class<?> t) {
String responseString = "";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Gson gson = new GsonBuilder().create();
//now we will try to convert the class to the specified type.
t = (Class<?>) gson.fromJson(responseString, t);
} catch (Exception e) {
responseString = e.toString();
}
return responseString;
Thanks a lot.
After some tries, I ended up with this code but I am still facing a null pointer exception.
MemberInfo mem = new MemberInfo();
TypeToken<MemberInfo> m = null ;
ServiceCaller.Post(getString(R.string.LoginService), values , m);
Gson gson = new GsonBuilder().create();
//now we will try to convert the class to the specified type.
t = (TypeToken<T>) gson.fromJson(responseString, (Type) t);
As far as I know, this is impossible. In order for one to do this, gson would have to be able to detect the correct class only from the serialized string. However, a single string can be interpreted in many valid ways. For instance, take an example on the gson website:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
BagOfPrimitives() {
// no-args constructor
}
}
Using Gson.toJson on an instance of this class results in the string:
{"value1":1,"value2":"abc"}
However, if I made another class identical to the first in all respects but name:
class SackOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
SackOfPrimitives() {
// no-args constructor
}
}
Then this would also serialize to the same string:
{"value1":1,"value2":"abc"}
My point is that given a single string like {"value1":1,"value2":"abc"}, there is no way for gson to determine whether it should deserialize it into an object of type BagOfPrimitives or type SackOfPrimitives. Therefore, you always have to provide gson with the correct type, because it wouldn't be possible for gson to figure it out by itself.
I have a String in java that might look like this:
String str = "Hello this is #David's first comment #excited"
I want to convert this string to a json object, but it throws an error when I use the below:
JSONObject json = new JSONObject(str);
I have found out that it throws an error due to the '#' symbol.
Is there any other way to convert the string to json, without much hassle ?
The problem is not so much the '#' symbols; it's that you are trying to parse the string as if it's already JSON. You probably want something like this:
JSONObject json = new JSONObject();
json.put("firstString", str);
String jsonString = json.toString();
or, more briefly (if all you want is a quoted JSON string:
String jsonString = JSONObject.valueToString(str);