Json parser converting null values to 0 - java

I am using net.sf.json library and using it to parse my refMap like:
Map<String, Group> myMap = new HashMap<String,Group>();
myMap = this.getGroupValues();
JSONObject jsonObj = new JSONObject();
jsonObj.putAll(refMap);
File jsonFile = new File("./TempJson.txt");
FileWriter writer = new FileWriter(jsonFile);
fileWriter.write(jsonObj.toString());
where my Group class is defined as:
class Group {
Double val;
Integer num;
Section sectionObj;
//..getters & setters
}
The Problem is this.getGroupValues() returns some Group objects where val/num (wrapper classes) values are 'null' and then JsonObject parser converts it to 0 like: "val":0,"num":0
while if sectionObj is null , parser keeps it as null as "sectionObj":null
How to get null values for wrapper class Objects too in json file ?

I would suggest using a different JSON library. For example, GSON will leave null values out of the serialized JSON text. When it is deserialized by GSON, those missing values are set to null in the new object.
Consider this example:
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
final String json = gson.toJson(new Group());
System.out.println(json);
Group g = gson.fromJson(json, Group.class);
System.out.println(g);
}
public static class Group {
Double val;
Integer num;
Section sectionObj;
// Getters and setters...
#Override
public String toString() {
return "val: '" + val + "' num: '" + num
+ "' sectionObj: '" + sectionObj + "'";
}
}
public static class Section {}
}
which outputs the following:
{}
val: 'null' num: 'null' sectionObj: 'null'

Related

How to convert single String containing a comma separated json values into a single json object?

I am getting some data which is a single string
"{"somekey": someValue}, {"someKey2": someValue}, {"someKey3": someValue}"
how would I return that as a single json object like this using java libraries?
{{"somekey": someValue}, {"someKey2": someValue}, {"someKey3": someValue}}
I have been trying to use the ObjectMapper class to read the value into a List but can't convert it.
List<String> list = mapper.readValue(jsonString, new TypeReference<List<String>> () {});
I have the option to retrieve the data in an array like this:
[{"somekey": someValue}, {"someKey2": someValue}, {"someKey3": someValue}]
but I still can't manage to convert it to a single json Object response
String jsonString = "{"somekey": someValue}, {"someKey2": someValue}, {"someKey3": someValue}";
Object object = new ObjectMapper().readValue(jsonString, Object.class);
Try this
If you have a JSON string that looks as follows:
String userJson = "[{'name': 'Alex','id': 1}, "
+ "{'name': 'Brian','id':2}, "
+ "{'name': 'Charles','id': 3}]";
And a corresponding POJO that looks as follows:
public class User
{
private long id;
private String name;
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
You could then use a library GSON to parse the JSON string into an array of User objects:
Gson gson = new Gson();
User[] userArray = gson.fromJson(userJson, User[].class);

How to convert an json response like that?

I have a json reponse like given below.Basically,I want to convert an object and use it.
[
{
"Id": 1290,
"N": "Türkiye",
"Fid": 196,
"EC": 10,
"CL": null,
"SID": 0
},
{
"Id": 1239,
"N": "Dünya",
"Fid": 152,
"EC": 63,
"CL": null,
"SID": 0
}
]
... Goes on
Here is what I have tried,I am using org.json library.
String jsonString = response.body().string(); // Getting json response and converting to string.
JSONObject jsonResponse = new JSONObject( jsonString ); // Not working
JSONArray jsonArray = new JSONArray( jsonString ); // Not working
JSONArray matches = new JSONArray( jsonString ).getJSONArray(0); // Not working
But I am gettin those errors
A JSONObject text must begin with '{' at 0 [character 1 line 1]
A JSONArray text must begin with '{' at 0 [character 1 line 1]
I have checked topics like Parse JSON Array without Key. But the json described not like mine.
Any idea what should ı do?
in Java you would first need to define a class which has all the attributes
public class MyClass {
private int Id;
private int N;
private int Fid;
private int EC;
private int CL;
private int Sid;
// getters, setters, no arg constructor
}
then you can use for example gson library to parse it like this:
MyClass[] myClassArray = gson.fromJson(jsonString , MyClass[].class)
I really recommend you to use the Gson library it's way better to perform data operations:
public class User {
int id;
String n;
int fid;
int ec;
String cl;
int sid;
public static User[] parse(String s){
return new GsonBuilder().create().fromJson(s, User[].class);
}
}
Have you looked into Google's Gson? It is really easy to use and you can both serialize and deserialize objects.
Here is an example:
public Company[] deserializeCompany() {
Gson gson = new Gson();
Company[] companies = gson.fromJson(companiesJSON, Company[].class);
return companies;
}
First you need to make a template class that has a member field for each key in the json. E.g. private String id for the 'Id' key in the json you provided. In my example it is the Company class.
Next you make a new Gson object using Gson gson = new Gson(); and use the .fromJson function supplying it both the Json array and the Object array type (which is of the form MyClass[].class).
First, your question is not to convert a JSON array without key. Second, there are many popular JSON libraries can achieve what you want such as org.json, Jackson, Gson and so on.
Here comes several examples:
With org.json, you can retrieve field values in a JSON array as follows:
JSONArray jsonResponse = new JSONArray(jsonStr);
System.out.println(jsonResponse.get(0).toString());
System.out.println("Id: " + jsonResponse.getJSONObject(0).get("Id"));
System.out.println("N : " + jsonResponse.getJSONObject(0).get("N"));
And the expected output should be:
{"Fid":196,"CL":null,"Id":1290,"N":"Türkiye","EC":10,"SID":0}
Id: 1290
N : Türkiye
With Jackson, you can retrieve field values in a JSON array as follows:
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, Object>> jsonResponse = objectMapper.readValue(jsonStr, new TypeReference<List<Map<String, Object>>>() {});
System.out.println(jsonResponse.toString());
System.out.println("Id: " + jsonResponse.get(0).get("Id"));
System.out.println("N : " + jsonResponse.get(0).get("N"));
And the expected output should be:
{Id=1290, N=Türkiye, Fid=196, EC=10, CL=null, SID=0}
Id: 1290
N : Türkiye
3. Furthermore, if you define a POJO as follows:
class MyObject {
private #JsonProperty("Id") int id;
private #JsonProperty("N") String n;
private #JsonProperty("Fid") int fid;
private #JsonProperty("EC") int ec;
private #JsonProperty("CL") int cl;
private #JsonProperty("SID") int sid;
//general getters, setters and toString
}
Then you can deserialize the JSON response to your POJO by:
ObjectMapper objectMapper = new ObjectMapper();
List<MyObject> jsonResponse = objectMapper.readValue(jsonStr, new TypeReference<List<MyObject>>() {});
System.out.println(jsonResponse.get(0).toString());
System.out.println("Id: " + jsonResponse.get(0).getId());
System.out.println("N : " + jsonResponse.get(0).getN());
And the expected output should be:
MyObject{id=1290, n='Türkiye', fid=196, ec=10, cl=0, sid=0}
Id: 1290
N : Türkiye

Java Gson parse Json object to array

I'm trying to parse the below Json using the Gson lib in Java. When using other languages, such as C#, this JSON is parsed into an array, however it seems Gson converts this into a set of java attributes (which to be honest, makes more sense to me). Does anyone know if I can change this behaviour of the Gson lib?
{
"Outer": {
"0": {
"Attr1": 12345,
"Attr2": 67890
},
"1": {
"Attr1": 54321,
"Attr2": 09876
}
}
}
The below code demonstrates how Gson parses the array as a JsonObject. To be clear, I realise I've referenced outer as a JsonObject but I was just doing this to demonstrate the code. If I try and reference outer as an JsonArray, the code fails.
String json = "{\"Outer\": { \"0\": { \"Attr1\": 12345, \"Attr2\": 67890 }, \"1\": { \"Attr1\": 54321, \"Attr2\": 09876 }}}";
Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setLenient()
.serializeNulls()
.create();
JsonObject jo = gson.fromJson(json, JsonObject.class);
JsonObject outer = jo.getAsJsonObject("Outer");
System.out.println(outer);
System.out.println(outer.isJsonArray());
Result:
{"0":{"Attr1":12345,"Attr2":67890},"1":{"Attr1":54321,"Attr2":"09876"}}
false
//edit
I'm using this current simple Json as an example, however my application of this code will be to parse Json that's of varying and unknown shape. I therefore need Gson to automatically parse this to an array so that the isJsonArray returns true.
TL;DR: See "Using Deserializer" section at the bottom for parsing straight to array.
That JSON does not contain any arrays. An array would use the [...] JSON syntax.
Normally, a JSON object would map to a POJO, with the name in the name/value pairs mapping to a field of the POJO.
However, a JSON object can also be mapped to a Map, which is especially useful when the names are dynamic, since POJO fields are static.
Using Map
The JSON object with numeric values as names can be mapped to a Map<Integer, ?>, e.g. to parse that JSON to POJOs, do it like this:
class Root {
#SerializedName("Outer")
public Map<Integer, Outer> outer;
#Override
public String toString() {
return "Root[outer=" + this.outer + "]";
}
}
class Outer {
#SerializedName("Attr1")
public int attr1;
#SerializedName("Attr2")
public int attr2;
#Override
public String toString() {
return "Outer[attr1=" + this.attr1 + ", attr2=" + this.attr2 + "]";
}
}
Test
Gson gson = new GsonBuilder().create();
Root root;
try (BufferedReader in = Files.newBufferedReader(Paths.get("test.json"))) {
root = gson.fromJson(in, Root.class);
}
System.out.println(root);
Output
Root[outer={0=Outer[attr1=12345, attr2=67890], 1=Outer[attr1=54321, attr2=9876]}]
Get as Array
You can then add a helper method to the Root class to get that as an array:
public Outer[] getOuterAsArray() {
if (this.outer == null)
return null;
if (this.outer.isEmpty())
return new Outer[0];
int maxKey = this.outer.keySet().stream().mapToInt(Integer::intValue).max().getAsInt();
Outer[] arr = new Outer[maxKey + 1];
this.outer.forEach((k, v) -> arr[k] = v);
return arr;
}
Test
System.out.println(Arrays.toString(root.getOuterAsArray()));
Output
[Outer[attr1=12345, attr2=67890], Outer[attr1=54321, attr2=9876]]
Using Deserializer
However, it would likely be more useful if the conversion to array is done while parsing, so you need to write a JsonDeserializer and tell Gson about it using #JsonAdapter:
class Root {
#SerializedName("Outer")
#JsonAdapter(OuterArrayDeserializer.class)
public Outer[] outer;
#Override
public String toString() {
return "Root[outer=" + Arrays.toString(this.outer) + "]";
}
}
class OuterArrayDeserializer implements JsonDeserializer<Outer[]> {
#Override
public Outer[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// Parse JSON array normally
if (json.isJsonArray())
return context.deserialize(json, Outer[].class);
// Parse JSON object using names as array indexes
JsonObject obj = json.getAsJsonObject();
if (obj.size() == 0)
return new Outer[0];
int maxKey = obj.keySet().stream().mapToInt(Integer::parseInt).max().getAsInt();
Outer[] arr = new Outer[maxKey + 1];
for (Entry<String, JsonElement> e : obj.entrySet())
arr[Integer.parseInt(e.getKey())] = context.deserialize(e.getValue(), Outer.class);
return arr;
}
}
Same Outer class and test code as above.
Output
Root[outer=[Outer[attr1=12345, attr2=67890], Outer[attr1=54321, attr2=9876]]]
I'll asume your JsonObject is a POJO class such like:
public Inner[] outer;
If you want an array of objects you can change your code to:
Inner[] jo = gson.fromJson(json, Inner[].class);
Jackson – Marshall String to JsonNode will be useful in your case.with following pom:-
//POM FILE
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
//JAVA CODE
//read json file data to String
byte[] jsonData = Files.readAllBytes(Paths.get("employee.txt"));
//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
//read JSON like DOM Parser
JsonNode rootNode = objectMapper.readTree(jsonData);
JsonNode idNode = rootNode.path("id");
System.out.println("id = "+idNode.asInt());
JsonNode phoneNosNode = rootNode.path("phoneNumbers");
Iterator<JsonNode> elements = phoneNosNode.elements();
while(elements.hasNext()){
JsonNode phone = elements.next();
System.out.println("Phone No = "+phone.asLong());
}
You can use the JsonNode class's method findParent findValue and findPath which reduce your code as compare to another parsing library.
Please refer below code
1.To get an array of Objects (outerArray)
2.You can extract a JsonArray (outerJsonArray) containing values of inner objects in Outer (in case keys aren't significant for further use)
String json = "{\"Outer\": { \"0\": { \"Attr1\": 12345, \"Attr2\": 67890 }, \"1\": { \"Attr1\": 54321, \"Attr2\": 09876 }}}";
Gson gson = new GsonBuilder().disableHtmlEscaping().setLenient().serializeNulls().create();
JsonObject jo = gson.fromJson(json, JsonObject.class);
JsonObject outer = jo.getAsJsonObject("Outer");
Object[] outerArray = outer.entrySet().toArray();
// outerArray: [0={"Attr1":12345,"Attr2":67890}, 1={"Attr1":54321,"Attr2":"09876"}]
JsonArray outerJsonArray = new JsonArray();
outer.keySet().stream().forEach(key -> {
outerJsonArray.add(outer.get(key));
});
//jsonArray=[{"Attr1":12345,"Attr2":67890},{"Attr1":54321,"Attr2":"09876"}]
System.out.println(outer);
System.out.println(outerJsonArray.isJsonArray() + " " + outerJsonArray);

org.JSONObject vs Map in Gson serialization [duplicate]

I have a POJO class as:
public class D{
private JSONObject profileData;
public JSONObject getProfileData ()
{
return profileData;
}
public void setProfileData (JSONObject profileData)
{
this.profileData = profileData;
}
}
Now I populate this class like:
for (int i =0; i<identities.size();i++){
D d = new D();
d.setProfileData(profileData);
dList.add(d);
}
I create JSON object for profileData from GSON using a HashMap:
profileDataInJson = new JSONObject(gson.toJson(map1));
Where the signature of profileDataInJson is: JSONObject profileDataInJson = null;
Now the resultant JSON is like:
"profileData":{"map":{"ioCinema":"firstValue","ioSIMAvailable":"firstKey","Name":"onePair"}}
Wherein I get an unwanted object called map inserted in my main profileData object.
However when I print this inside the loop I get
{`"ioCinema":"firstValue","ioSIMAvailable":"firstKey","Name":"onePair"}`
Whish is exactly what I want inside profileData object, without nesting the map object.
How do I solve this?
"I am already aware that I can achieve this by converting the type of profileData in D class from JSONObject to String, which will induce escape characters - However I am looking for a generic solution"
EDIT:
map1 is constructed in two ways, depending on user input and both ways are as follows:
if (args.length >= 4 && args[1].equalsIgnoreCase("onePair")) {
map1 = new HashMap<>();
String key1 = args[2];
String value1 = args[3];
map1.put(key1, value1);
profileDataInJson = new JSONObject(gson.toJson(map1));
}
And:
if (args.length >= 1 && args[0].equalsIgnoreCase("update")) {
if (args.length >= 2)
profileData.setName(args[1] != null ? args[1] : "");
if (args.length >= 3)
profileData.setSIMAvailable(args[2] != null ? args[2] : "");
profileDataInJson = new JSONObject(profileData);
}
Signature: ProfileData profileData = new ProfileData();
The thing which puzzles me is when I try to traverse profileData and try to fetch the json object by name "map" I get a nullPointer exception
You don't need to use Gson to convert hashmap to a json object.
Simply use:
profileDataInJson = new JSONObject(map);
Add custom serializer to Gson, so that Gson serialize the org JSON as expected by you.
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JSONObject.class, new JsonSerializer<JSONObject>() {
#Override
public JsonElement serialize(final JSONObject src, final Type typeOfSrc,
final JsonSerializationContext context) {
return new JsonParser().parse(src.toString()).getAsJsonObject();
}
});
gsonBuilder.create().toJson(map1);
This will return {"ioCinema":"firstValue","ioSIMAvailable":"firstKey","Name":"onePair"}

Create list of java objects from json

I have following json which i need to convert into list of java objects.
{
"model":[
{
"syscall_1":"execve",
"syscall_2":"brk"
},
{
"syscall_1":"brk",
"syscall_2":"access"
},
{
"syscall_1":"access",
"syscall_2":"mmap"
},
{
"syscall_1":"mmap",
"syscall_2":"access"
}
]
}
I am using gson and its TypeToken>(){}.getType() API ,however I am bit confused about how my objects should look corresponding to input json.
How can I use TypeToken in this scenario?
Another option (not using the type token, but still achieves what you want) would be to parse the entire json object, then access the model array like so:
import com.google.gson.Gson;
import java.util.List;
public class TestMe {
public static void main(String[] args) {
String jsonSt2 = "{\"model\":[{\"syscall_1\":\"execve\",\"syscall_2\":\"brk\"},{\"syscall_1\":\"brk\",\"syscall_2\":\"access\"},{\"syscall_1\":\"access\",\"syscall_2\":\"mmap\"},{\"syscall_1\":\"mmap\",\"syscall_2\":\"access\"}]}";
System.out.println("your json: " + jsonSt2);
ModelObject object = new Gson().fromJson(jsonSt2, ModelObject.class);
System.out.println("Created Model object, array size is " + object.model.size());
for (ModelItem mi : object.model) {
System.out.println(mi.syscall_1 + " " + mi.syscall_2);
}
}
}
class ModelObject {
List<ModelItem> model;
}
class ModelItem {
String syscall_1;
String syscall_2;
}
Output
Created Model object, array size is 4
execve brk
brk access
access mmap
mmap access
mmap access
If you can use org.json to parse and construct list objects, you can try this.
String jsonSt2 = "{\"model\":[{\"syscall_1\":\"execve\",\"syscall_2\":\"brk\"},{\"syscall_1\":\"brk\",\"syscall_2\":\"access\"},{\"syscall_1\":\"access\",\"syscall_2\":\"mmap\"},{\"syscall_1\":\"mmap\",\"syscall_2\":\"access\"}]}";
List<Model> models = new ArrayList<>();
JSONObject jsonModelObject = new org.json.JSONObject(jsonSt2);
Object modelObject = jsonModelObject.get("model");
if (modelObject instanceof JSONArray) {
JSONArray itemsArray =(JSONArray) modelObject;
for (int index = 0; index < itemsArray.length(); index++) {
Model model = new Model();
JSONObject modelItereative = (JSONObject) itemsArray.get(index);
model.setSyscall_1(modelItereative.getString("syscall_1"));
model.setSyscall_2(modelItereative.getString("syscall_1"));
models.add(model);
}
}else if(modelObject instanceof JSONObject){
Model model = new Model();
JSONObject modelItereative = (JSONObject) modelObject;
model.setSyscall_1(modelItereative.getString("syscall_1"));
model.setSyscall_2(modelItereative.getString("syscall_1"));
models.add(model);
}
for(Model d22:models){
System.out.println(d22.getSyscall_1() + " " + d22.getSyscall_2());
}

Categories

Resources