Converting JSON objects in Android with gson - java

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.

Related

get a key value pair from a String json (simple object)

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

JSON Schema Validation With typecasting feature

Please suggest how to perform typecasting before validation of JSON Schema in Java. I've achieved the same in NodeJS using json-schema-validation-pipeline package. Below code snippet for reference (where param1 was actually of type string as provided from backend API).
var ValidationPipeline = require('json-schema-validation-pipeline');
var V = ValidationPipeline.V;
var validate = ValidationPipeline([
{
$schema: {
'param1': V(Number).min(60)
}
},
{ $cast: { param1: Number } }
]);
So basically, I am looking for equivalent solution in Java for above code snippet. Thanks
Assign it to POJO model class of JAVA and once you have this native object then you can typecast to anything as its in language operation For example-
File file = new File("json/student.json");
// get json as buffer
BufferedReader br = new BufferedReader(new FileReader(file));
// obtained Gson object
Gson gson = new Gson(); //import com.google.gson.Gson;
// called fromJson() method and passed incoming buffer from json file
// passed student class reference to convert converted result as Student object
Student student = gson.fromJson(br, Student.class);

After converting an object to a String, how can I get the object back from the string again?

I was creating a simple android application in which I am converting an object to String. How can I re-convert the object from the string?
I am converting my object to String using the following line of code.
String convertedString = object.toString();
You can't**, because that is not what the toString method is for. It's used to make a readable representation of your Object, but it's not meant for saving and later reloading.
What you are looking for instead is Serialization. See this tutorial here to get started:
http://www.tutorialspoint.com/java/java_serialization.htm
** Technically you could, but you shouldn't.
You can do it in two ways:
Java Serialization
Using Gson library (more simple), remember the the purpose of this lib is to convert simply json to object and viceversa when working with REST services.
Hope it helps
You can use Serialization to convert object to string and vise versa:
String serializedObject = "";
// serialize the object
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(myObject);
so.flush();
serializedObject = bo.toString();
} catch (Exception e) {
System.out.println(e);
}
// deserialize the object
try {
byte b[] = serializedObject.getBytes();
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
MyObject obj = (MyObject) si.readObject();
} catch (Exception e) {
System.out.println(e);
}
Use Java Serialization for doing same.
Go with below link for better understand how to convert java object.
Ex. http://www.geeksforgeeks.org/serialization-in-java/
Also You can go with this link:
How to convert the following json string to java object?

Dynamic JSON issue

My JSON Structure will vary depend on the request. But the content inside each element remain same. For Example:
JSON1:
{
"h1": {
"s1":"s2"
},
"c1": {
"t1:""t2"
}
}
JSON2:
{
"h1": {
"s1":"s2"
},
"c2": {
"x1:""x2"
}
}
In the above example, elements inside h1,c1 and c2 are constant. Please let me know how to convert JSON to JAVA Object
Regards
Udhaya
First of all You need to understand Json Structure cause above format is incorrect visit this
and this
And you can use Google Gson or Json for parsing the result json String .
"t1:""t2" json format incorrect
Used
"t1":"t2"
Instead of
"t1:""t2"
and also used
"x1": "x2"
Instead of
"x1:""X2"
Code to take in java
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonsubObject = jsonObject.getJSONObject("h1");
String s1 = jsonsubObject.getString("s2");
JSONObject jsonsubObject1 = jsonObject.getJSONObject("c1");
String t1 = jsonsubObject1 .getString("t2");
}
catch (JSONException e) {
e.printStackTrace();
}
Use Google Gson:
Gson gson = new Gson();
ClassName object;
try {
object = gson.fromJson(json, ClassName.class);
} catch (com.google.gson.JsonSyntaxException ex) {
//the json wasn't valid json
}
String validJson = gson.toJson(obj); //obj is an instance of any class
json must be a valid JSON String
import org.json.JSONObject;
you can simple pass your data in constructor of JSONObject it automatically handle, you need to throws JSONException which may occur during conversion id format of data is not correct
String data = "{'h1':{'s1':'s2'},'c1':{'t1:''t2'}}";
JSONObject jsnobject = new JSONObject(data);

How to convert String to Json

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

Categories

Resources