GVKun编程网logo

使用Java读取JSON中的嵌套键的值(Jackson)(jsonobject 获取嵌套key)

4

在本文中,我们将带你了解使用Java读取JSON中的嵌套键的值在这篇文章中,我们将为您详细介绍使用Java读取JSON中的嵌套键的值的方方面面,并解答Jackson常见的疑惑,同时我们还将给您一些技巧

在本文中,我们将带你了解使用Java读取JSON中的嵌套键的值在这篇文章中,我们将为您详细介绍使用Java读取JSON中的嵌套键的值的方方面面,并解答Jackson常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的Fastjson和Jackson序列化和读取json的性能实测、Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)、Jackson-Java bean到JSON字符串:大写变量在JSON中转换为小写、Jackson将json string转为Object,org.json读取json数组的实例

本文目录一览:

使用Java读取JSON中的嵌套键的值(Jackson)(jsonobject 获取嵌套key)

使用Java读取JSON中的嵌套键的值(Jackson)(jsonobject 获取嵌套key)

我是来自Python的新Java程序员。我有正在收集/返回为带有嵌套键的JSON的天气数据,而且我不了解在这种情况下如何提取值。我敢肯定这个问题已经被问过了,但是我发誓我已经用Google搜索了很多东西,但是我似乎找不到答案。现在我正在使用json-
simple,但我尝试切换到Jackson,但仍然不知道如何执行此操作。由于Jackson /
Gson似乎是使用最频繁的库,因此,我很想看看使用其中一个库的示例。下面是数据示例,后面是我到目前为止编写的代码。

{
    "response": {
        "features": {
            "history": 1
        }
     },"history": {
        "date": {
            "pretty": "April 13,2010","year": "2010","mon": "04","mday": "13","hour": "12","min": "00","tzname": "America/Los_Angeles"
        },...
    }
}

主功能

public class Tester {

    public static void main(String args[]) throws MalformedURLException,IOException,ParseException {
        WundergroundAPI wu =  new WundergroundAPI("*******60fedd095");

        JSONObject json = wu.historical("San_Francisco","CA","20100413");

        System.out.println(json.toString());
        System.out.println();
        //This only returns 1 level. Further .get() calls throw an exception
        System.out.println(json.get("history"));
    }
}

函数’historical’调用另一个返回JSONObject的函数

public static JSONObject readJsonFromUrl(URL url) throws MalformedURLException,ParseException {

    InputStream inputStream = url.openStream();

    try {
        JSONParser parser = new JSONParser();
        BufferedReader buffReader = new BufferedReader(new InputStreamReader(inputStream,Charset.forName("UTF-8")));

        String jsonText = readAll(buffReader);
        JSONObject json = (JSONObject) parser.parse(jsonText);
        return json;
    } finally {
        inputStream.close();
    }
}

Fastjson和Jackson序列化和读取json的性能实测

Fastjson和Jackson序列化和读取json的性能实测

偶然间看到的阿里出品的Fastjson,网上对这个json包好评如潮,性能胜Jackson10倍。
本人本着眼见为实的想法,自己测试一下两者的性能比较。

###测试### POJO对象名字为User,具体代码就不贴了,里面有两个属性,分别是int类型的id和String类型的name,很简单的一个类。

测试程序(只是简单的测试下,这里并未深究其中的各种构造方法)

    public class MyMain {
	private static final int TEST_CASE_NUM = 1000;
	public static void main(String args[]) throws IOException {

		List<User> users = new ArrayList<User>();
		Random random = new Random();

		for (int i = 0; i < TEST_CASE_NUM; i++) {
			User user = new User();
			user.setId(random.nextInt(10));
			user.setName("123");
			users.add(user);
		}

		Monitor.begin();
		for (User u : users){
			String s = JSON.toJSONString(u);
		}
		Monitor.end("serilization of fastjson");

		Monitor.begin();
                                    /**
		 * 这里仅创建一个ObjectMapper实例
		 * 而网上的很多测试程序中,把实例的创建过程
		 * 加入到了for循环中,因此测出来的序列化性能
		 * 有10倍之差,其实其中大部分都消耗在了ObejectMapper
		 * 实例创建上。
		 */
		ObjectMapper objectMapper = new ObjectMapper();
		for (User u : users){
			String s = objectMapper.writeValueAsString(u);
		}
		long endjackson = System.currentTimeMillis();
		Monitor.end("serilization of jackson");


		List<String> strs = new ArrayList<String>();
		for (int j = 0; j < TEST_CASE_NUM; j++) {
			String s = new String("{\"id\":1,\"name\":\"123\"}");
			strs.add(s);
		}

		Monitor.begin();
		for (String s : strs){
			User user = JSON.parseObject(s,User.class);
		}
		Monitor.end("reading string by fastjson");

		Monitor.begin();
                                    ObjectMapper obj = new ObjectMapper();
		for (String s : strs){
			User user = obj .readValue(s,User.class);
		}
		Monitor.end("reading string by jackson");
	}
}

运行程序得到输出:

    serilization of fastjson use 158 ms
serilization of jackson use 339 ms
reading string by fastjson use 49 ms
reading string by jackson use 73 ms

多次运行后结果相差甚微,比例关系基本保持稳定。由此可见fastjson并未如网上传言那般,性能较之于jackson提升10倍。如果将ObjectMapper实例的创建过程也从计时器中提取出来,哪么Jackson与fastjson的序列化性能几乎相同。
然而在反序列方面,fastjson以巨大的优势领先Jackson,将测试的用例个数增加至1000000,得到的输出为:

    reading string by fastjson use 505 ms
reading string by jackson use 1051 ms

fastjson几乎只需要Jackson的一半时间,这个表现相当亮眼。

在这里我们反序列化的字符串是按照实体类中属性的顺序排列的,如果打乱一下顺序呢?
这里还是使用1000000个测试用例,得到的输出结果为:

    reading string by fastjson use 715 ms
reading string by jackson use 1049 ms

因为fastjson默认开启了sort field martch优化算法,打乱顺序之后性能下降,但仍然领先Jackson不少。

###总结### 这次测试使用的是1.9.31版本的Jackson和1.1.39版本的fasijson,测试结果表名fastjson和Jackson在序列化性能上相差不大(主要ObjectMapper类新建实例耗费不少时间),但是在反序列化方面,fastjson要明显领先于Jackson。

Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)

Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)

在将json发布到Spring Controller时获得上述异常.看来Jackson Mapper无法反序列化json. CategoryDTO注释为:

@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,property="@id",scope = CategoryDTO.class)

JSON:

[
   {
      "categories":[
         {
            "@id":27048,"name":"Sportbeha's","description":null,"parent":{
               "@id":22416,"name":"fitness","parent":{
                  "@id":21727,"name":"Collectie","description":null
               }
            }
         },{
            "@id":27050,"parent":{
               "@id":24474,"name":"Voetbal","parent":21727
            }
         }
      ]
   },{
      "categories":[
         {
            "@id":27048,"parent":21727
            }
         }
      ]
   }
]

Java代码:

@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,scope = CategoryDTO.class)
@JsonIgnoreProperties(ignoreUnkNown = true)
public class CategoryDTO implements Serializable{

    private Long id;
    private String name;
    private String description;
    private CategoryDTO parent;

    @JsonIgnore
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public CategoryDTO getParent() {
        return parent;
    }

    public void setParent(CategoryDTO parent) {
        this.parent = parent;
    }

}


**Spring Controller :** 

    @RequestMapping(value = "/categories",method = RequestMethod.POST,consumes =  "application/json;charset=UTF-8",produces = "application/json;charset=UTF-8")
    public ResponseEntity

问题似乎与这片json有关:

"parent":{
    "@id":21727,"description":null
}

它存在于数组中的两个对象中.

最佳答案
如果对每个嵌套对象使用相同的CategoryDto,

"parent": 21727

因为杰克逊期待一个对象,所以不会反序列化.要仅使用id反序列化父CategoryDto,您需要POST以下JSON:

"parent": {
    "@id": 21727
}

Jackson-Java bean到JSON字符串:大写变量在JSON中转换为小写

Jackson-Java bean到JSON字符串:大写变量在JSON中转换为小写

我正在使用ObjectMapper的writeValueAsString方法将Java bean转换为JSON字符串,其中Java
bean中的大写变量被更改为JSON字符串中的小写字母。实施了Jackson 2.7.4版本。菜豆样品-

public class BaseBean {private static final long serialVersionUID = 3947489072259877540L;private int _iXId;private String _sPNR;private ArrayList _alMinPriced = new ArrayList<TermBean>();public int getXId() {    return _iXId;}public void setXId(int id) {    _iXId = id;}public String getPNRNumber() {    return _sPNR;}public void setPNRNumber(String _spnr) {    _sPNR = _spnr;}public ArrayList getMinPriced() {    return _alMinPriced;}public void setMinPriced(ArrayList minPriced) {    _alMinPriced = minPriced;}public void setMinPriced(TermBean bnTerm) {    _alMinPriced.add(bnTerm);}

}

之前,我们使用net.sf.json.JSON和JSONSerializer将Java bean转换为JSON。生成的JSON字符串与我们使用的Java
bean具有相似的命名。由于性能问题,我想对此进行更改并实施Jackson。

限制:我们无法更改Java
bean的命名约定,因为这些bean来自较旧的项目,并且几乎没有范围来更改bean中的变量名,甚至在每个bean中添加json属性。

我已经尝试了下面的代码,但是没有用

ObjectMapper mapper = new ObjectMapper();mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);

另外,我尝试了自定义的PropertyNamingStrategy,但对此还不清楚。

编辑:

net.sf.json.JSON 生成了上述Bean的JSON字符串,如下所述:

{"XId":11,"PNRNumber":"123456789","minPriced":[{"name":"JSON"},{"name":"simple"}]}

Jackson 为上述bean生成了JSON字符串,如下所述:

{"xid":11,"pnrnumber":"123456789","minPriced":[{"name":"JSON"},{"name":"Jackson"}]}

如您所见,在jackson中,“ XId”转换为“ xid”,在jackson中,“ PNRNumber”转换为“ pnrnumber”。

Jackson中是否有任何可用的配置更改来避免此类修改。或如何处理这种情况。

答案1

小编典典

使用了以下罐子:

  1. 杰克逊核心2.7.4.jar
  2. 杰克逊注释2.7.4.jar
  3. jackson-databind-2.7.4.jar

步骤1:请按以下方式编写以下Mixin:

import java.util.ArrayList;import com.fasterxml.jackson.annotation.JsonProperty;public abstract class MixIn {    @JsonProperty("PNRNumber")    abstract String getPNRNumber();    @JsonProperty("XId")    abstract int getXId();    @JsonProperty("minPriced")    abstract ArrayList getMinPriced();}

步骤2:请按照以下步骤编写模块:

import com.fasterxml.jackson.databind.module.SimpleModule;public class MyModule extends SimpleModule{  public MyModule() {    super("ModuleName");  }  @Override  public void setupModule(SetupContext context){    context.setMixInAnnotations(BaseBean.class, MixIn.class);     }}

步骤3:现在是时候获取json String了,如下所示:

TermBean bean1=new TermBean("JSON");TermBean bean2=new TermBean("simple");ArrayList list=new ArrayList();        list.add(bean1);        list.add(bean2);BaseBean bb=new BaseBean();        bb.setXId(11);        bb.setPNRNumber("123456789");        bb.setMinPriced(list);ObjectMapper mapper = new ObjectMapper();Module myModule = new MyModule();mapper.registerModule(myModule);        String jsonInString = mapper.writeValueAsString(bb);      System.out.printf( "JSON: %s", jsonInString );

输出:

JSON:{“ XId”:11,“ PNRNumber”:“ 123456789”,“ minPriced”:[{“ name”:“ JSON”},{“
name”:“ simple”}]}}

希望这可以帮助。

Jackson将json string转为Object,org.json读取json数组的实例

Jackson将json string转为Object,org.json读取json数组的实例

下面小编就为大家带来一篇Jackson将json string转为Object,org.json读取json数组的实例,具有很好的参考价值,希望对大家有所帮助

从json文件读取json string或者自定义json string,将其转为object。下面采用的object为map,根据map读取json的某个数据,可以读取第一级的数据name,后来发现想转成JsonArray读取”red“时没撤了,只好用了其他方法。

最后用org.json包解决了(readJsonArray函数),有空再看看有没有更好的办法。

JSON文件如下:

{ "name":"name", "id":"id", "color":[ {"red":"red","blue":"blue"}, {"white":"white"} ] }

代码如下:

package com; import org.codehaus.jackson.map.ObjectMapper; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Map; /** * Hello World! * */ public class JsonAnalysis { private static final Logger LOG = LoggerFactory.getLogger(JsonAnalysis.class); public static void main(String[] args) throws FileNotFoundException { String jsonString = "{"address":"address","name":"name","id":"1","email":"email"}"; FileReader fileReader = new FileReader("E:\JsonAnalysis\src\test.json"); String fileString = readFile(fileReader); //Json字符串转java对象,比如转为Map对象读取其中数据 Map map = null; Map mapFile = null; try { map = readValue(jsonString, Map.class); mapFile = readValue(fileString, Map.class); } catch (Exception e) { e.printstacktrace(); LOG.error("ReadValue occur exception when switch json string to map"); } System.out.println(map != null ? map.get("id") : null); if (mapFile==null){ LOG.info("Json map form file is empty"); return; } System.out.println(mapFile.get("name")); try { readJsonArray(fileString); } catch (Exception e) { e.printstacktrace(); } } //Json string to object private static T readValue(String jsonStr, Class valueType) throws Exception{ ObjectMapper objectMapper = new ObjectMapper(); try { // Object object = objectMapper.readValue(jsonStr,Object.class); return objectMapper.readValue(jsonStr,valueType); } catch (IOException e) { e.printstacktrace(); } return null; } //Read file and to string private static String readFile(FileReader fileReader){ BufferedReader bufferedReader = new BufferedReader(fileReader); StringBuilder fileStr = new StringBuilder(); try { String eachLine; while ((eachLine=bufferedReader.readLine())!=null){ fileStr.append(eachLine); } return fileStr.toString(); } catch (IOException e1) { e1.printstacktrace(); LOG.error("Occur exception when read file,file={}",fileReader); return null; } } //根据json string 获取json array,读取数据( 注意该部分引用的是org.json 包) private static void readJsonArray(String jsonStr) throws Exception { JSONObject jsonObject = new JSONObject(jsonStr); JSONArray jsonArray = jsonObject.getJSONArray("color"); JSONObject jsonObject1 = jsonArray.getJSONObject(0); System.out.println(jsonObject1.get("red")); } }

以上这篇Jackson将json string转为Object,org.json读取json数组的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持小编。

关于使用Java读取JSON中的嵌套键的值Jackson的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Fastjson和Jackson序列化和读取json的性能实测、Jackson Mapper没有反序列化JSON – (无法读取JSON:已经有了id(java.lang.Integer)的POJO)、Jackson-Java bean到JSON字符串:大写变量在JSON中转换为小写、Jackson将json string转为Object,org.json读取json数组的实例的相关知识,请在本站寻找。

本文标签: