I am new to json. I am able to create a json from servlet. But I am bounded to create a json like below-
{
"name":"Employee",
"children":[{
"name":"Subho"
},
{
"name":"jeet",
"children":[{
"name":"rahul"
},
{
"name":"abhijit"
}]
}]
}
But what I create is like-
{
"children":[
{"name":"Culture"},
{"name":"Salary"},
{"name":"Work"},
{"name":"Economy"}
],
"name":"Employee"
}
My servlet code is-
public class ActionServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Random r = new Random();
int low = 0;
int high = 5;
int R = r.nextInt(high - low) + low;
/*Sample data for child nodes actual data will be called here*/
String arr[] = {"Culture", "Salary", "Work", "Economy"};
/*Responsible for creation of the child nodes and their names */
Map<String, String> mapping = new HashMap<String, String>();
EntryListContainer entryListContainer = new EntryListContainer();
List<Entry> entryList1 = new ArrayList<Entry>();
for (int i = 0; i < R; i++) {
/*Model object for the Link*/
Entry entry1 = new Entry();
entry1.setChildren(arr[i]);
entryList1.add(entry1);
}
entryListContainer.setEntryList1(entryList1);
/*Root node this will collapse and get back to Original position on click*/
entryListContainer.setName("Employee");
mapping.put("entryList1","name");
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping)).create();
System.out.println(gson.toJson(entryListContainer));
String json = null;
/*conversion of the json from the generated java object*/
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
json = new Gson().toJson(gson);
System.out.println(json);
response.getWriter().write(gson.toJson(entryListContainer));
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
This is the EntryListContainer class
public class EntryListContainer {
private List<Entry> children;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setEntryList1(List<Entry> entryList1) {
this.children = entryList1;
}
public List<Entry> getEntryList1() {
return children;
}
This is the DynamicFieldNamingStrategy class
public class DynamicFieldNamingStrategy implements FieldNamingStrategy{
private Map<String, String> mapping;
public DynamicFieldNamingStrategy(Map<String, String> mapping) {
this.mapping = mapping;
}
#Override
public String translateName(Field field) {
String newName = mapping.get(field.getName());
if (newName != null) {
return newName;
}
return field.getName();
}
This servlet code is creating a json. Here 1st I create all the children nodes and put them in a list (here entryList1), and then put them in a hashmap. But what I create is not fulfilling my requirement..
Please anyone help me with this..
If we will put your JSon to jsoneditoronline, we get:
{
"name": "Employee",
"children": [
{
"name": "Subho"
},
{
"name": "jeet",
"children": [
{
"name": "rahul"
},
{
"name": "abhijit"
}
]
}
]
}
Now we can see that each Node has name and list of other Nodes:
Node
public class Node {
private String name = "";
private List<Node> children;
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Code
Node child = new Node();
child.setName("Employee");
List<Node> list = new ArrayList<Node>();
Node subChild = new Node();
subChild.setName("Subho");
list.add(subChild);
subChild = new Node();
subChild.setName("jeet");
List<Node> sublist = new ArrayList<Node>();
Node subsubChild = new Node();
subsubChild.setName("Subho");
sublist.add(subsubChild);
subsubChild = new Node();
subsubChild.setName("Subho");
sublist.add(subsubChild);
subChild.setChildren(sublist);
list.add(subChild);
child.setChildren(list);
Gson gson = new Gson();
String output = gson.toJson(child);
Output:
{"name":"Employee","children":[{"name":"Subho"},{"name":"jeet","children":[{"name":"Subho"},{"name":"Subho"}]}]}
Related
{
"status": true,
"message": [
{
"ID": 1,
"TFrom": "b",
"TTo": "c"
},
{
"ID": 2,
"TFrom": "b",
"TTo": "c"
},
{
"ID": 3,
"TFrom": "b",
"TTo": "c"
}
]
}
This is my JSON result, I'm using Android/Java and what I want is to get each object in the "message" array separated in an array, because each one of them should be in a list item.
Which means my ListView is going to view the "message" content in lists.
It's more like this:
list1= [{"ID": 1, "TFrom": "b", "TTo": "c"}]
list2= [{"ID": 2, "TFrom": "b", "TTo": "c"}]
Message Object Class:
public class MessagesObject {
boolean status;
List<AMessage> message;
public List<AMessage> getMessage() {
return message;
}
public void setMessage(List<AMessage> message) {
this.message = message;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
AMessage Class:
public class AMessage {
int ID;
String TFrom;
String TTo;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getTFrom() {
return TFrom;
}
public void setTFrom(String TFrom) {
this.TFrom = TFrom;
}
public String getTTo() {
return TTo;
}
public void setTTo(String TTo) {
this.TTo = TTo;
}
}
Usage :
String json="you json string";
MessagesObject messagesObject = new Gson().fromJson(jsonToParse, MessagesObject.class);
Ref Gson :
implementation 'com.google.code.gson:gson:2.8.2'
Output:
I'm not sure what you really want, but if you really would like to convert an array into list of arrays, ie.
[1, 2, 3] => [[1], [2], [3]]
You can use this code as a starting point.
List<List<T>> YOUR_LIST_OF_LISTS = message.stream().map((e) -> {
ArrayList<T> temp = new ArrayList<>();
temp.add(e);
return temp;
}).collect(Collectors.toList());
Replace T with some datatype you want, in your case probably JSONObject.
Not android specific, just java codes. I'm not sure why you would want to do something like this tho. Comment below if this is not what you intended.
JSONObject heroObject = data.getJSONObject("favorite");
JSONArray jarray=heroObject.getJSONArray("message");
ArrayList<HashMap<String,String>> array=new ArrayList<>();
//now looping through all the elements of the json array
for (int i = 0; i < jarray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = jarray.getJSONObject(i);
HashMap<String,String> inner=new HashMap<String, String>();
inner.put("id", heroObject.getString("ID"));
inner.put("from", heroObject.getString("TFrom"));
inner.put("to", heroObject.getString("TTo"));
array.add(inner);
}
Use gson library. check below how to implement in project.
build.gradle
implementation 'com.google.code.gson:gson:2.7'
Then create MessageModel.java and MessageBaseModel.java.
MessageModel.java
public class MessageModel {
#SerializedName("ID")
int id;
#SerializedName("TFrom")
String tFrom;
#SerializedName("TTo")
String tTo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String gettFrom() {
return tFrom;
}
public void settFrom(String tFrom) {
this.tFrom = tFrom;
}
public String gettTo() {
return tTo;
}
public void settTo(String tTo) {
this.tTo = tTo;
}
}
MessageBaseModel.java
public class MessageBaseModel {
#SerializedName("status")
boolean status;
#SerializedName("message")
ArrayList<MessageModel> messageModels = new ArrayList<>();
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public ArrayList<MessageModel> getMessageModels() {
return messageModels;
}
public void setMessageModels(ArrayList<MessageModel> messageModels) {
this.messageModels = messageModels;
}
}
Use below code in your main activity:(note: result is your JSON result)
MessageBaseModel messageBaseModel=new Gson().fromJson(result.toString() , MessageBaseModel.class);
ArrayList<MessageModel> messageModels = MessageBaseModel.getMessageModels();
Check below example to get the output:
messageModels.get(0) is your first message object
messageModels.get(0).getId()=1
messageModels.get(0).gettFrom()=b
messageModels.get(1).getId()=2
messageModels.get(2).getId()=3
Sorry for my english.
Try this
List<Map<String,String>> list = new ArrayList<>();
try
{
JSONArray messageArray = response.getJSONArray("message");
for (int i = 0;i<messageArray.length(); i++)
{
Map<String,String> map = new HashMap<>();
JSONObject jsonObject = messageArray.getJSONObject(i);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext())
{
String key = keys.next();
String value = jsonObject.getString(key);
map.put(key,value);
}
list.add(map);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
{
{
"1234": {
"name": "bob"
}
},
{
"5678": {
"name": "dan"
}
}
}
I have a class representing name (and other fields, I've just made it simple for this question). But the each element is key'd with the id of the person.
I've tried several things including:
class Name {
String Name;
//getter and setter
}
class NameId {
String id;
Name name;
//getter and setters
}
//json is the string containing of the above json
ArrayList<NameId> map = objectMapper.readValue(json, ArrayList.class);
for (Object m : map) {
LinkedHashMap<String, NameId> l = (LinkedHashMap)m;
Map<String, NameId> value = (Map<String, NameId>) l;
//System.out.println(l);
//System.out.println(value);
for (Object key : value.keySet()) {
System.out.println("key: " + key);
System.out.println("obj: " + value.get(key));
NameId nameId = (NameId)value.get(key);
}
}
The problem I have is it doesn't allow that cast to NameId. The error I get is:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to NameId
Any ideas on the best way to parse such a json string like this properly?
Your json is malformed. You need the square brackets around it otherwise it isn't considered a json array. If your json looks like (for example)
[
{
"1234" : {
"name" : "dan"
}
},
{
"5678" : {
"name" : "mike"
}
}
]
you can write a custom deserializer for the object mapper. See the working example below:
public static void main(String... args) throws Exception {
String testJson = "[{ \"1234\" : { \"name\" : \"dan\" } },{ \"5678\" : { \"name\" : \"mike\" } }]";
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(NameId.class, new MyDeserializer());
mapper.registerModule(module);
ArrayList<NameId> map = mapper.readValue(testJson.getBytes(), new TypeReference<List<NameId>>() {
});
for (NameId m : map) {
System.out.println(m.id);
System.out.println(m.name.name);
System.out.println("----");
}
}
#JsonDeserialize(contentUsing = MyDeserializer.class)
static class NameId {
String id;
Name name;
//getter and setters
}
static class Name {
String name;
//getter and setter
}
static class MyDeserializer extends JsonDeserializer<NameId> {
#Override
public NameId deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = p.getCodec().readTree(p);
Map.Entry<String, JsonNode> nodeData = node.fields().next();
String id = nodeData.getKey();
String name = nodeData.getValue().get("name").asText();
Name nameObj = new Name();
nameObj.name = name;
NameId nameIdObj = new NameId();
nameIdObj.name = nameObj;
nameIdObj.id = id;
return nameIdObj;
}
}
try this
Iterator<String> iterator1 =outerObject.keys();
while(iterator1.hasNext())
{
JsonObject innerObject=outerObject.getJsonObject(iterator1.next());
Iterator<String> iterator2=innerObject.keys();
while(iterator2.hasNext()){
String name=innerObject.getString(iterator2.next());
}
}
Your json is not valid. Maybe a little bit different:
{
"1234": {
"name": "bob"
},
"5678": {
"name": "dan"
}
}
And you could model something like:
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And instead of attemping to use a list, use a map:
Map<Integer, Person> map = new ObjectMapper().readValue(json,
TypeFactory.defaultInstance()
.constructMapType(Map.class, Integer.class, Person.class));
no custom deserializer needed.
first, the json file as #klaimmore suggested (named test.json):
{
"1234": {
"name": "bob"
},
"5678": {
"name": "dan"
}
}
Secondly. here's the 2 separate class files:
#JsonDeserialize
public class Name {
String name;
public Name(String name) {
this.name = name;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
and
#JsonDeserialize
public class NameId {
Name name;
String id;
/**
* #return the id
*/
public String getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* #return the name
*/
public Name getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(Name name) {
this.name = name;
}
}
and the extra simple json parser class.
public class JsonParser {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String jsonString = new String(Files.readAllBytes(Paths.get("test.json")));
ObjectMapper mapper = new ObjectMapper();
Map<String,NameId> nameIdList = mapper.readValue(jsonString, new TypeReference<Map<String,NameId>>(){});
nameIdList.entrySet().forEach(nameIdEntry -> System.out.println("name id is: " + nameIdEntry.getKey() +
" and name is: " + nameIdEntry.getValue().getName().getName()));
}
}
also. this is pretty much a dupe of How to convert json string to list of java objects. you should read this.
My json string is:
{
"recordsTotal":1331,
"data":[
{
"part_number":"3DFN64G08VS8695 MS",
"part_type":"NAND Flash",
"id":1154,
"manufacturers":[
"3D-Plus"
]
},
{
"part_number":"3DPM0168-2",
"part_type":"System in a Package (SiP)",
"id":452,
"manufacturers":[
"3D-Plus"
]
},
{
"part_number":"3DSD1G16VS2620 SS",
"part_type":"SDRAM",
"id":269,
"manufacturers":[
"3D-Plus"
]
}
]
}
This code lets me access the two highest level elements:
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
System.out.println("data : " + jsonObject.get("data"));
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
But what I want to do is iterate over all the objects inside "data" and create a list of part_numbers. How do I do that?
JsonArray is an Iterable<JsonElement>. So you can use for in loop.
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
final JsonArray data = jsonObject.getAsJsonArray("data");
System.out.println("data : " + data);
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
List<String> list = new ArrayList<String>();
for (JsonElement element : data) {
list.add(((JsonObject) element).get("part_number").getAsString());
}
Suppose class Name for Json Model is Example.
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Example {
#SerializedName("recordsTotal")
private Integer recordsTotal;
#SerializedName("data")
private List<Datum> data = null;
public Integer getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(Integer recordsTotal) {
this.recordsTotal = recordsTotal;
}
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
}
And suppose List of Data class name is Datum :-
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Datum {
#SerializedName("part_number")
private String partNumber;
#SerializedName("part_type")
private String partType;
#SerializedName("id")
private Integer id;
#SerializedName("manufacturers")
private List<String> manufacturers = null;
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartType() {
return partType;
}
public void setPartType(String partType) {
this.partType = partType;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getManufacturers() {
return manufacturers;
}
public void setManufacturers(List<String> manufacturers) {
this.manufacturers = manufacturers;
}
}
And then through Gson library we can convert json to java Model :
Example example = new Gson().fromJson(jsonString, new TypeToken<Example>() {}.getType());
Now we can get list of data though example model :-
List<Datum> dataList = example.getData();
From dataList you can traverse and get all info.
If partNmber List we need then we can get in this way :-
List<String> partNumberList = new ArrayList<>();
for (Datum data : dataList) {
partNumberList.add(data.getPartNumber());
}
The given code will not guaranteed to 100% equivalent but it will help you to work.
First you have to create the class for your data objects:
class mydata {
public String part_name;
public String part_type;
public int Id;
public String manufacturers;
}
Your main method should look like
public static void main(String[] args) {
JSONObject obj = new JSONObject();
List<mydata> sList = new ArrayList<mydata>();
mydata obj1 = new mydata();
obj1.setValue("val1");
sList.add(obj1);
mydata obj2 = new mydata();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
}
For futher exploration you can use that link:
https://gist.github.com/codebutler/2339666
I have to make a tree like JSON structure with Java where I have a parent node with multiple children in it and so on. This is my code I have partially done this one but not completely successful to do it ..here is the output I need
{
"name": "Culture",
"children": [
{
"name": "Salary"
},
{
"name": "Work",
"children": [
{
"name": "Effort"
},
{
"name": "trust"
}
]
}
]
}
but what I am generating is
{"name":"Culture",[{"name":"Salary"},{"name":"Work"},{"name":"Effort"}],"name":"Work",[{"name":"Culture"},{"name":"Work"}]}
Here is my code:
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class ParentChildApp {
public static class EntryListContainer {
public List<Entry> children = new ArrayList<Entry>();
public Entry name;
}
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
}
public static void main(String[] args) {
EntryListContainer elc1 = new EntryListContainer();
elc1.name = new Entry("Culture");
elc1.children.add(new Entry("Salary"));
elc1.children.add(new Entry("Work"));
elc1.children.add(new Entry("Effort"));
EntryListContainer elc2 = new EntryListContainer();
elc2.name = new Entry("Work");
elc2.children.add(new Entry("Culture"));
elc2.children.add(new Entry("Work"));
ArrayList<EntryListContainer> al = new ArrayList<EntryListContainer>();
Gson g = new Gson();
al.add(elc1);
al.add(elc2);
StringBuilder sb = new StringBuilder("{");
for (EntryListContainer elc : al) {
sb.append(g.toJson(elc.name).replace("{", "").replace("}", ""));
sb.append(",");
sb.append(g.toJson(elc.children));
sb.append(",");
}
String partialJson = sb.toString();
if (al.size() > 1) {
int c = partialJson.lastIndexOf(",");
partialJson = partialJson.substring(0, c);
}
String finalJson = partialJson + "}";
System.out.println(finalJson);
}
}
Do this:
package stackoverflow.questions;
import com.google.gson.*;
import java.util.ArrayList;
import java.util.List;
public class ParentChildApp {
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
private List<Entry> children;
public void add(Entry node){
if (children == null)
children = new ArrayList<Entry>();
children.add(node);
}
}
public static void main(String[] args) {
Entry workNode = new Entry("Work");
workNode.add(new Entry("Effort"));
workNode.add(new Entry("Trust"));
Entry salaryNode = new Entry("Salary");
Entry cultureNode = new Entry("Culture");
cultureNode.add(salaryNode);
cultureNode.add(workNode);
Gson g = new Gson();
System.out.println(g.toJson(cultureNode));
}
}
You will get exactly the JSON you are looking for.
I have to make a Json which will form a tree like structure.I have written a java code that is forming a structure like that but it does not satisfy the purpose.Here where i have done so far..This is my java class..
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GsonProgram {
public static void main(String... args) throws Exception {
String arr[] = {"Culture", "Salary", "Work", "Effort"};
EntryListContainer entryListContainer = new EntryListContainer();
List<Entry> entryList1 = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
Entry entry1 = new Entry();
Entry entry2 = new Entry();
entry1.setChildren(arr[i]);
entryList1.add(entry1);
entryList2.add(entry2);
entryListContainer.setEntryList1(entryList1);
entryListContainer.setEntryList1(entryList2);
/*Root node this will collapse and get back to Original position on click*/
entryListContainer.setName("Employee");
entryListContainer.setName("manager");
}
Map<String, String> mapping = new HashMap<>();
mapping.put("entryList1", "name");
mapping.put("entryList2", "name");
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping)).create();
System.out.println(gson.toJson(entryListContainer));
}
}
class DynamicFieldNamingStrategy implements FieldNamingStrategy {
private Map<String, String> mapping;
public DynamicFieldNamingStrategy(Map<String, String> mapping) {
this.mapping = mapping;
}
#Override
public String translateName(Field field) {
String newName = mapping.get(field.getName());
if (newName != null) {
return newName;
}
return field.getName();
}
}
class EntryListContainer {
private List<Entry> entryList1;
public void setEntryList1(List<Entry> entryList1) {
this.entryList1 = entryList1;
}
public List<Entry> getEntryList1() {
return entryList1;
}
}
class Entry {
private String name;
public String getChildren() {
return name;
}
public void setChildren(String name) {
this.name = name;
}
}
and this is the generated json
{
"name":[{
"name":"Salary"
},{
"name":"Salary"
},{
"name":"Work"
},{
"name":"Doller"
}]
}
But i want this structure...
{
"name":"Employee",
"children":[{
"name":"Salary"
},{
"name":"Salary"
},{
"name":"Work"
},{
"name":"Doller"
}]
}
I need this format of json.somebody please help....
The pseudo class structure should be:
class DynamicFieldNamingStrategy{
private String name;
private List<Entry> children;
}
GsonProgram
public class GsonProgram {
public static void main(String... args) throws Exception {
Entry entry1 = new Entry();
entry1.setChildren("Salary");
Entry entry2 = new Entry();
entry2.setChildren("Salary");
Entry entry3 = new Entry();
entry3.setChildren("Work");
Entry entry4 = new Entry();
entry4.setChildren("Doller");
EntryListContainer entryListContainer = new EntryListContainer();
ArrayList<Entry> entryList1 = new ArrayList<Entry>();
entryList1.add(entry1);
entryList1.add(entry2);
entryList1.add(entry3);
entryList1.add(entry4);
entryListContainer.setEntryList1(entryList1);
entryListContainer.setName("Employee");
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("entryList1", "name");
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping)).create();
System.out.println(gson.toJson(entryListContainer));
}
}
EntryListContainer
class EntryListContainer {
private List<Entry> children;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setEntryList1(List<Entry> entryList1) {
this.children = entryList1;
}
public List<Entry> getEntryList1() {
return children;
}
}
Output:
{
"children": [
{
"name": "Salary"
},
{
"name": "Salary"
},
{
"name": "Work"
},
{
"name": "Doller"
}
],
"name": "Employee"
}