String str={"a":1,"b":2,"c":3};
转化成json格式 返回到前端页面解析
字符串转json
给前端?说反了吧,应该是你java
里的对象,转换成json
字符串然后返回给前端吧!如果是这样,可以使用Jackson 2
库,maven
配置依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
然后代码:
import java.math.BigDecimal;
import java.util.List;
public class Staff {
private String name;
private int age;
private String position;
//getters and setters
}
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Jackson2Example {
public static void main(String[] args) {
Jackson2Example obj = new Jackson2Example();
obj.run();
}
private void run() {
ObjectMapper mapper = new ObjectMapper();
Staff staff = new Staff();
staff.setName("Hanmeimei");
staff.setAge(31);
staff.setPosition("Developer");
try {
// 转换对象成字符串
String jsonInString = mapper.writeValueAsString(staff);
System.out.println(jsonInString);
} catch (Exception e) {
e.printStackTrace();
}
}
8 回答6.4k 阅读
1 回答4.2k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
2 回答3.2k 阅读
2 回答3.9k 阅读
3 回答1.7k 阅读✓ 已解决
1 回答2k 阅读✓ 已解决
可以用GSON解析,方便,简单,强大