2,100
社区成员
发帖
与我相关
我的任务
分享
result:[{"key":"duo2","value_list":[{"value":"du21"},{"value":"du22"}]},{"key":"duo1","value_list":[{"value":"du11"},{"value":"du12"}]}]
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class JsonCovert {
public static void main(String[] args) {
// TODO Auto-generated method stub
String jsonString="[{\"checked_id\":\"10002\",\"content_title\":\"duo1\",\"content\":\"du11\"},{\"checked_id\":\"10002\",\"content_title\":\"duo1\",\"content\":\"du12\"},{\"checked_id\":\"10002\",\"content_title\":\"duo2\",\"content\":\"du21\"},{\"checked_id\":\"10002\",\"content_title\":\"duo2\",\"content\":\"du22\"}]";
Gson gson=new Gson();
List<InnerObject> data=gson.fromJson(jsonString, new TypeToken<List<InnerObject>>(){}.getType());
Map<String,CovertObject> covertData=new Hashtable<>();
for(InnerObject iob:data){
String k=iob.getContent_title();
if(!covertData.containsKey(k)){
covertData.put(k, new CovertObject(k,iob.getContent()));
}else{
covertData.get(k).addCovertObject(iob.getContent());
}
}
/*测试
Set<String> keySet=covertData.keySet();
for(String ks:keySet){
System.out.println("key:"+ks);
List<CovertObjectType> valList=covertData.get(ks).getValue_list();
for(CovertObjectType cot:valList){
System.out.println("value:"+cot);
}
}*/
String covertJsonString =gson.toJson(covertData.values());
System.out.println("result:"+covertJsonString);
}
}
class CovertObject{
private final String key;
private final List<CovertObjectType> value_list=new ArrayList<>();
public CovertObject(String title,String content) {
super();
this.key = title;
this.value_list.add(new CovertObjectType(content));
}
public String getKey() {
return key;
}
public List<CovertObjectType> getValue_list() {
return value_list;
}
public void addCovertObject(String content){
this.value_list.add(new CovertObjectType(content));
}
}
class CovertObjectType{
private final String value;
public CovertObjectType(String value) {
super();
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return "CovertObjectType [value=" + value + "]";
}
}
class InnerObject{
private int checked_id;
private String content_title;
private String content;
public int getChecked_id() {
return checked_id;
}
public void setChecked_id(int checked_id) {
this.checked_id = checked_id;
}
public String getContent_title() {
return content_title;
}
public void setContent_title(String content_title) {
this.content_title = content_title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "InnerObject [checked_id=" + checked_id + ", content_title=" + content_title + ", content=" + content
+ "]";
}
}